一、题目
我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。
在本题里,字母板为board = [“abcde”, “fghij”, “klmno”, “pqrst”, “uvwxy”, “z”],如下所示。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/alphabet-board-path/description/
二、C++解法
我的思路及代码
刚开始没有注意到可以用任何达成目标的最短序列返回,导致我对z进行了特殊处理,写了屎山代码,随便看看吧,简单版本看参考代码
class Solution {
public:
string alphabetBoardPath(string target) {
int row = 0;
int col = 0;
int currow=0;
int curcol=0;
string ans;
for(int i=0;i<target.size();i++){
row = (target[i]-'a')/5;
col = (target[i]-'a')%5;
row>currow?ans.append(row == 5?(row-currow-1):(row-currow),'D'):ans.append(currow-row,'U');
col>curcol?ans.append(col-curcol,'R'):ans.append(curcol - col,'L');
(row == 5&&row!=currow)?ans.append("D!"):ans.append("!");
currow = row;
curcol = col;
}
return ans;
}
};
- 时间复杂度:时间复杂度: O(n×(r+c)),其中 n 表示给定字符串的长度,r 表示字母板的行数, c 表示字母板的列数。每次移动到新的字符生成移动指令时,需要的时间复杂度为 r+c,一共需要生成指令 n 次,因此时间复杂度为 O(n×(r+c))
- 空间复杂度:O(1)
官方参考代码
优先走左边和上边可以避开z的问题
class Solution {
public:
string alphabetBoardPath(string target) {
int cx = 0, cy = 0;
string res;
for (char c : target) {
int nx = (c - 'a') / 5;
int ny = (c - 'a') % 5;
if (nx < cx) {
res.append(cx - nx, 'U');
}
if (ny < cy) {
res.append(cy - ny, 'L');
}
if (nx > cx) {
res.append(nx - cx, 'D');
}
if (ny > cy) {
res.append(ny - cy, 'R');
}
res.push_back('!');
cx = nx;
cy = ny;
}
return res;
}
};
- 时间复杂度:时间复杂度: O(n×(r+c)),其中 n 表示给定字符串的长度,r 表示字母板的行数, c 表示字母板的列数。每次移动到新的字符生成移动指令时,需要的时间复杂度为 r+c,一共需要生成指令 n 次,因此时间复杂度为 O(n×(r+c))
- 空间复杂度:O(1)
文章讨论了LeetCode上的一个问题,即如何从字母板的(0,0)位置出发,找到到达目标字符串每个字符的最短路径。作者提供了两种C++解法,一种未考虑最优路径,另一种优化了路径选择,避免了特殊处理。两种解法的时间复杂度均为O(n×(r+c)),空间复杂度为O(1)。
247

被折叠的 条评论
为什么被折叠?



