You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).
Given the string word, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Input: word ="CAKE"Output: 3Explanation: Using two fingers, one optimal way to type "CAKE"is:Finger 1 on letter 'C'-> cost =0Finger 1 on letter 'A'-> cost = Distance from letter 'C' to letter 'A'=2Finger 2 on letter 'K'-> cost =0Finger 2 on letter 'E'-> cost = Distance from letter 'K' to letter 'E'=1Total distance =3
Input: word ="HAPPY"Output: 6Explanation: Using two fingers, one optimal way to type "HAPPY"is:Finger 1 on letter 'H'-> cost =0Finger 1 on letter 'A'-> cost = Distance from letter 'H' to letter 'A'=2Finger 2 on letter 'P'-> cost =0Finger 2 on letter 'P'-> cost = Distance from letter 'P' to letter 'P'=0Finger 1 on letter 'Y'-> cost = Distance from letter 'A' to letter 'Y'=4Total distance =6
We can use dynamic programming to track the minimum distance for each possible position of the two fingers as we type the word. By considering all possible finger moves at each step, we ensure the optimal solution.
classSolution {
publicintminimumDistance(String word) {
int[][] pos =newint[26][2];
for (int i = 0; i < 26; ++i) {
pos[i][0]= i / 6; pos[i][1]= i % 6;
}
int n = word.length();
int[][] dp =newint[n+1][27];
for (int[] row : dp) Arrays.fill(row, 1000000000);
dp[0][26]= 0;
for (int i = 0; i < n; ++i) {
int cur = word.charAt(i) -'A';
for (int f = 0; f <= 26; ++f) {
int cost = dp[i][f];
int d1 = (f == 26) ? 0 : Math.abs(pos[f][0]- pos[cur][0]) + Math.abs(pos[f][1]- pos[cur][1]);
dp[i+1][cur]= Math.min(dp[i+1][cur], cost + d1);
if (i == 0) continue;
int prev = word.charAt(i-1) -'A';
int d2 = Math.abs(pos[prev][0]- pos[cur][0]) + Math.abs(pos[prev][1]- pos[cur][1]);
dp[i+1][f]= Math.min(dp[i+1][f], cost + d2);
}
}
int ans = 1000000000;
for (int v : dp[n]) ans = Math.min(ans, v);
return ans;
}
}