Alphabet Board Path LeetCode solution in C++

1
class Solution {
2
public:
3
string alphabetBoardPath(string target) {
4
string ans = "";
5
int prevRow = 0;
6
int prevCol = 0;
7
int curRow = 0;
8
int curCol = 0;
9
for (int i = 0; i < target.length(); i++) {
10
prevCol = curCol;
11
prevRow = curRow;
12
curRow = (target[i] - 'a') / 5;
13
curCol = (target[i] - 'a') % 5;
14
if (curRow == 5 and abs(curCol - prevCol) > 0) {
15
curRow--;
16
}
17
if (curRow - prevRow > 0) {
18
ans += string((curRow - prevRow), 'D');
19
} else {
20
ans += string((prevRow - curRow), 'U');
21
}
22
if (curCol - prevCol > 0) {
23
ans += string((curCol - prevCol), 'R');
24
} else {
25
ans += string((prevCol - curCol), 'L');
26
}
27
if (((target[i] - 'a') / 5) == 5 and abs(curCol - prevCol) > 0) {
28
ans += 'D';
29
curRow++;
30
}
31
ans += '!';
32
}
33
return ans;
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0