文章目录
更多LeetCode题解
On an alphabet board, we start at position (0, 0)
, corresponding to character board[0][0]
.
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
.
We may make the following moves:
'U'
moves our position up one row, if the square exists;'D'
moves our position down one row, if the square exists;'L'
moves our position left one column, if the square exists;'R'
moves our position right one column, if the square exists;'!'
adds the characterboard[r][c]
at our current position(r, c)
to the answer.
Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
Example 1:
Input: target = “leet”
Output: “DDR!UURRR!!DDD!”
Example 2:
Input: target = “code”
Output: “RR!DDRR!UUL!R!”
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.
Solution
求得当前字母的位置相对于前一字母的位置的x
y
位移即可。
要注意的是z
这个字母,从它出去只能先上后右,进入它只能先做后下。
class Solution {
public:
string alphabetBoardPath(string target) {
string path;
int x_index = 0;
int y_index = 0;
for(int i=0;i<target.size();i++){
int x_curr_index = (target[i]-'a')/5;
int y_curr_index = (target[i]-'a')%5;
if(target[i]=='z'){
insertYAlphabet(path, y_curr_index-y_index);
insertXAlphabet(path, x_curr_index-x_index);
}
else{
insertXAlphabet(path, x_curr_index-x_index);
insertYAlphabet(path, y_curr_index-y_index);
}
path.push_back('!');
x_index = x_curr_index;
y_index = y_curr_index;
}
return path;
}
void insertXAlphabet(string &path, int n){
if(n>=0){
for(int i=0;i<n;i++){
path.push_back('D');
}
}
else{
for(int i=0;i<abs(n);i++){
path.push_back('U');
}
}
}
void insertYAlphabet(string &path, int n){
if(n>=0){
for(int i=0;i<n;i++){
path.push_back('R');
}
}
else{
for(int i=0;i<abs(n);i++){
path.push_back('L');
}
}
}
};