二指輸入法定製鍵盤在 XY 平面上的佈局如上圖所示,其中每個大寫英文字母都位於某個座標處,例如字母 A 位於座標 (0,0),字母 B 位於座標 (0,1),字母 P 位於座標 (2,3) 且字母 Z 位於座標 (4,1)。
給你一個待輸入字符串 word
,請你計算並返回在僅使用兩根手指的情況下,鍵入該字符串需要的最小移動總距離。座標 (x1,y1) 和 (x2,y2) 之間的距離是 |x1 - x2| + |y1 - y2|。
注意,兩根手指的起始位置是零代價的,不計入移動總距離。你的兩根手指的起始位置也不必從首字母或者前兩個字母開始。
示例 1:
輸入:word = "CAKE" 輸出:3 解釋: 使用兩根手指輸入 "CAKE" 的最佳方案之一是: 手指 1 在字母 'C' 上 -> 移動距離 = 0 手指 1 在字母 'A' 上 -> 移動距離 = 從字母 'C' 到字母 'A' 的距離 = 2 手指 2 在字母 'K' 上 -> 移動距離 = 0 手指 2 在字母 'E' 上 -> 移動距離 = 從字母 'K' 到字母 'E' 的距離 = 1 總距離 = 3
示例 2:
輸入:word = "HAPPY" 輸出:6 解釋: 使用兩根手指輸入 "HAPPY" 的最佳方案之一是: 手指 1 在字母 'H' 上 -> 移動距離 = 0 手指 1 在字母 'A' 上 -> 移動距離 = 從字母 'H' 到字母 'A' 的距離 = 2 手指 2 在字母 'P' 上 -> 移動距離 = 0 手指 2 在字母 'P' 上 -> 移動距離 = 從字母 'P' 到字母 'P' 的距離 = 0 手指 1 在字母 'Y' 上 -> 移動距離 = 從字母 'A' 到字母 'Y' 的距離 = 4 總距離 = 6
示例 3:
輸入:word = "NEW" 輸出:3
示例 4:
輸入:word = "YEAR" 輸出:7
提示:
2 <= word.length <= 300
- 每個
word[i]
都是一個大寫英文字母。
難點:四種情況DP,要想清楚:
//四種情況
dp[i][chi1][j]=min(dp[i-1][chi2][j]+dis(chi1,chi2),dp[i][chi1][j]);//左手打兩次
dp[i][j][chi1]=min(dp[i-1][j][chi2]+dis(chi1,chi2),dp[i][j][chi1]);//右手打兩次
dp[i][chi2][chi1]=min(dp[i][chi2][chi1],dp[i-1][chi2][j]+dis(j,chi1));//先右手然後左手
dp[i][chi1][chi2]=min(dp[i][chi1][chi2],dp[i-1][j][chi2]+dis(j,chi1));//先左手然後右手
class Solution {
public:
inline int dis(int x,int y)
{
return abs(x/6-y/6)+abs(x%6-y%6);
}
int minimumDistance(string word) {
int len=word.size();
int dp[305][26][26];
for(int i=0;i<len;i++)
{
for(int j=0;j<26;j++)
{
for(int k=0;k<26;k++)
{
dp[i][j][k]=INT_MAX>>1;
}
}
}
int k=word[0]-'A';
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
dp[0][i][j]=min(dis(i,k),dis(j,k));
}
}
for(int i=1;i<len;i++)
{
int chi1=word[i]-'A',chi2=word[i-1]-'A';
for(int j=0;j<26;j++)
{
//四種情況
dp[i][chi1][j]=min(dp[i-1][chi2][j]+dis(chi1,chi2),dp[i][chi1][j]);//左手打兩次
dp[i][j][chi1]=min(dp[i-1][j][chi2]+dis(chi1,chi2),dp[i][j][chi1]);//右手打兩次
dp[i][chi2][chi1]=min(dp[i][chi2][chi1],dp[i-1][chi2][j]+dis(j,chi1));//先右手然後左手
dp[i][chi1][chi2]=min(dp[i][chi1][chi2],dp[i-1][j][chi2]+dis(j,chi1));//先左手然後右手
}
}
int ans=INT_MAX;
for(int i=0;i<26;i++)
{
ans=min(ans,dp[len-1][word[len-1]-'A'][i]);
ans=min(ans,dp[len-1][i][word[len-1]-'A']);
}
return ans;
}
};