8000 1138 Alphabet Board Path · malipramod/leetcode-js@2865d21 · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 2865d21

Browse files
committed
1138 Alphabet Board Path
1 parent 57ea7f1 commit 2865d21

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string} target
3+
* @return {string}
4+
*/
5+
var alphabetBoardPath = function (target) {
6+
let result = '';
7+
let x = 0, y = 0;
8+
for (let c = 0; c < target.length; c++) {
9+
let i = Math.floor((target.charCodeAt(c) - 97) / 5)
10+
let j = Math.floor((target.charCodeAt(c) - 97) % 5);
11+
if (i > x) {
12+
while (x != i) {
13+
if (x == 4 && y > 0)
14+
break;
15+
result += "D";
16+
x++;
17+
}
18+
} else {
19+
while (x != i) {
20+
result += "U";
21+
x--;
22+
}
23+
}
24+
if (j > y) {
25+
while (y != j) {
26+
result += "R";
27+
y++;
28+
}
29+
} else {
30+
while (y != j) {
31+
result += "L";
32+
y--;
33+
}
34+
}
35+
if (x != i) {
36+
result += "D";
37+
x++;
38+
}
39+
result += "!";
40+
}
41+
return result;
42+
}
43+
44+
45+
console.log(alphabetBoardPath('code'))
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Alphabet Board Path
2+
3+
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].
4+
5+
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.
6+
7+
We may make the following moves:
8+
9+
'U' moves our position up one row, if the position exists on the board;
10+
11+
'D' moves our position down one row, if the position exists on the board;
12+
13+
'L' moves our position left one column, if the position exists on the board;
14+
15+
'R' moves our position right one column, if the position exists on the board;
16+
17+
'!' adds the character board[r][c] at our current position (r, c) to the answer.
18+
(Here, the only positions that exist on the board are positions with letters on them.)
19+
20+
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.
21+
22+
## Example 1
23+
24+
Input:
25+
26+
target = "leet"
27+
28+
Output: "DDR!UURRR!!DDD!"
29+
30+
## Example 2
31+
32+
Input:
33+
34+
target = "code"
35+
36+
Output: "RR!DDRR!UUL!R!"
37+
38+
## Constraints
39+
40+
1 <= target.length <= 100
41+
42+
target consists only of English lowercase letters.

0 commit comments

Comments
 (0)
0