/*
* @lc app=leetcode id=1138 lang=cpp
*
* [1138] Alphabet Board Path
*/
// @lc code=start
class Solution {
public:
// a->b
string getPath(int a,int b) {
if(a == b) return "!";
string ans;
string suffix;
if(a == 25) {
ans += 'U';
a -= 5;
}else if(b == 25){
suffix = "D";
b -= 5;
}
if(a < b){
while(a/5 != b/5){
ans += 'D';
a += 5;
}
}else if(b < a){
while(a/5 != b/5){
ans += 'U';
b += 5;
}
}
if(a < b){
for(int i=0;i<b-a;i++) ans += 'R';
}else if(b < a){
for(int i=0;i<a-b;i++) ans += 'L';
}
ans += suffix + '!';
return ans;
}
string alphabetBoardPath(string target) {
string base = "abcdefghijklmnopqrstuvwxyz";
string ans;
int last = 0;
for(int i=0;i<target.size();i++){
for(int j=0;j<base.size();j++){
if(base[j] == target[i]) {
ans += getPath(last, j);
last = j;
}
}
}
return ans;
}
};
// @lc code=end
No.267 - LeetCode[1138] Alphabet Board Path
最新推荐文章于 2024-05-15 12:57:31 发布