Skip to content

Commit 113af51

Browse files
committed
1138. 字母板上的路径
1 parent 94fccbc commit 113af51

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@
196196
|988|[从叶结点开始的最小字符串](https://leetcode.cn/problems/smallest-string-starting-from-leaf/)|[JavaScript](./algorithms/smallest-string-starting-from-leaf.js)|Medium|
197197
|1002|[查找共用字符](https://leetcode.cn/problems/find-common-characters/)|[JavaScript](./algorithms/find-common-characters.js)|Easy|
198198
|1005|[K 次取反后最大化的数组和](https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/)|[JavaScript](./algorithms/maximize-sum-of-array-after-k-negations.js)|Easy|
199+
|1138|[字母板上的路径](https://leetcode.cn/problems/alphabet-board-path/)|[JavaScript](./algorithms/alphabet-board-path.js)|Medium|
199200
|1038|[从二叉搜索树到更大和树](https://leetcode.cn/problems/binary-search-tree-to-greater-sum-tree/)|[JavaScript](./algorithms/binary-search-tree-to-greater-sum-tree.js)|Medium|
200201
|1047|[删除字符串中的所有相邻重复项](https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/)|[JavaScript](./algorithms/remove-all-adjacent-duplicates-in-string.js)|Easy|
201202
|1233|[删除子文件夹](https://leetcode.cn/problems/remove-sub-folders-from-the-filesystem/)|[JavaScript](./algorithms/remove-sub-folders-from-the-filesystem.js)|Medium|

algorithms/alphabet-board-path.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 1138. 字母板上的路径
3+
* @param {string} target
4+
* @return {string}
5+
*/
6+
var alphabetBoardPath = function (target) {
7+
let result = "";
8+
let prevRow = 0;
9+
let prevCol = 0;
10+
11+
for (let i = 0; i < target.length; i++) {
12+
const index = target[i].charCodeAt() - 97;
13+
const currRow = Math.floor(index / 5);
14+
const currCol = index % 5;
15+
16+
const rowDiff = Math.abs(currRow - prevRow);
17+
const colDiff = Math.abs(currCol - prevCol);
18+
19+
// 优先 `上移` 和 `左移` 避免 'z' 字符的问题
20+
if (currRow < prevRow) {
21+
result += "U".repeat(rowDiff);
22+
}
23+
if (currCol < prevCol) {
24+
result += "L".repeat(colDiff);
25+
}
26+
if (currRow > prevRow) {
27+
result += "D".repeat(rowDiff);
28+
}
29+
if (currCol > prevCol) {
30+
result += "R".repeat(colDiff);
31+
}
32+
result += "!";
33+
prevRow = currRow;
34+
prevCol = currCol;
35+
}
36+
return result;
37+
};

0 commit comments

Comments
 (0)