710149. Special Keyboard 2
Special Keyboard 2
Slug: special-keyboard-2 Difficulty: Medium Id: 710149 Topic Tags: Strings, Data Structures Company Tags: None
Summary
The Special Keyboard 2 problem involves a keyboard with a unique character set. The goal is to find the minimum number of presses required to type out all possible strings using this special keyboard.
Given a string str representing the special keyboard's character set and another string target representing the target string, return the minimum number of presses needed to type out the target string using the special keyboard. Each character in the target string can be replaced by any character in the special keyboard that is lexicographically smaller (i.e., alphabetically before).
Detailed Explanation
To solve this problem, we can use a dynamic programming approach. We will create a 2D array dp where dp[i][j] represents the minimum number of presses required to type out the first i characters of the target string using the special keyboard.
Here's a step-by-step breakdown of the solution:
- Initialize the
dparray with a size of(target.length + 1) x (str.length + 1)and set all elements to infinity. - Set
dp[0][j] = jfor allj, because we need one press for each character in the special keyboard to type out an empty target string. - Iterate through the target string from left to right:
- For each character
tin the target string, iterate through the special keyboard from left to right:- For each character
sin the special keyboard, calculate the minimum number of presses required to type out the firsticharacters of the target string using the special keyboard that replaces the current charactertwiths. - Update
dp[i][j] = min(dp[i][j], dp[i-1][k] + 1)wherekis the index of the smallest character in the special keyboard that is lexicographically smaller thant.
- For each character
- For each character
- Return
dp[target.length][0], which represents the minimum number of presses required to type out the entire target string using the special keyboard.
Time complexity: O(target.length * str.length) Space complexity: O(target.length * str.length)
Optimized Solutions
Java
int minPresses(String str, String target) {
int[][] dp = new int[target.length + 1][str.length + 1];
for (int i = 0; i <= target.length; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= str.length; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= target.length; i++) {
char t = target.charAt(i - 1);
for (int j = 1; j <= str.length; j++) {
char s = str.charAt(j - 1);
if (t >= s) {
dp[i][j] = dp[i - 1][j] + 1;
} else {
int minPresses = Integer.MAX_VALUE;
for (int k = 0; k < j; k++) {
if (s <= str.charAt(k)) {
minPresses = Math.min(minPresses, dp[i - 1][k] + 1);
}
}
dp[i][j] = minPresses;
}
}
}
return dp[target.length][0];
}