题目
- 字母板上的路径
我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。
在本题里,字母板为board = [“abcde”, “fghij”, “klmno”, “pqrst”, “uvwxy”, “z”],如下所示。
我们可以按下面的指令规则行动:
如果方格存在,'U' 意味着将我们的位置上移一行;
如果方格存在,'D' 意味着将我们的位置下移一行;
如果方格存在,'L' 意味着将我们的位置左移一列;
如果方格存在,'R' 意味着将我们的位置右移一列;
'!' 会把在我们当前位置 (r, c) 的字符 board[r][c] 添加到答案中。
(注意,字母板上只存在有字母的位置。)
返回指令序列,用最小的行动次数让答案和目标 target 相同。你可以返回任何达成目标的路径。
示例 1:
输入:target = “leet”
输出:“DDR!UURRR!!DDD!”
示例 2:
输入:target = “code”
输出:“RR!DDRR!UUL!R!”
提示:
1 <= target.length <= 100
target 仅含有小写英文字母。
代码
class Solution {
public static char[][] board = new char[][]{{'a', 'b', 'c', 'd', 'e'}, {'f', 'g', 'h', 'i', 'j'}, {'k', 'l', 'm', 'n', 'o'}, {'p', 'q', 'r', 's', 't'}, {'u', 'v', 'w', 'x', 'y'}, {'z'}};
public static String result = "";
public int i = 0; // 二维数组里的列
public int j = 0; // 二维数组里的行
public String alphabetBoardPath(String target) {
result = "";
int amount = target.length();
for (int i = 0; i < amount; i++) {
if (target.charAt(i) == 'z') helpZ();// 因为最后一个z是单独一行会比较难处理所以单独处理。
else help(target.charAt(i));
}
return result;
}
public void helpZ() {
while (i > 0) { // 移到最左边
result += "L";
i--;
}
while (j < 5) { // 再往下移,防止越界
result += "D";
j++;
}
result += "!";
return;
}
public void help(char target) {
if (board[j][i] == target) {
result += "!";
return;
} else if (target - board[j][i] > 0) { // 目标值比当前索引所在的值大
if (target - board[j][i] >= (5 - i)) {
result += "D";
j++;
} else {
result += "R";
i++;
}
help(target);
} else if (target - board[j][i] < 0) { // 目标值比索引值小
if (board[j][i] - target > i) {
result += "U";
j--;
} else {
result += "L";
i--;
}
help(target);
}
}
}