Execution of All Suffix Instructions Staying in a Grid LeetCode solution in Java

1
class Solution {
2
public int[] executeInstructions(int n, int[] startPos, String s) {
3
// Make array of length equal to string length
4
int ans[] = new int[s.length()];
5

6
// Now use two for loops
7
for (int i = 0; i < s.length(); i++) {
8
// countmoves will keep on counting the valid moves from i to s.length
9
int countMoves = 0;
10
int yIndex = startPos[0];
11
int xIndex = startPos[1];
12
for (int j = i; j < s.length(); j++) {
13

14
if (s.charAt(j) == 'R') {
15
xIndex++;
16
}
17
if (s.charAt(j) == 'L') {
18
xIndex--;
19
}
20
if (s.charAt(j) == 'U') {
21
yIndex--;
22
}
23
if (s.charAt(j) == 'D') {
24
yIndex++;
25
}
26
if (xIndex < 0 || xIndex >= n || yIndex < 0 || yIndex >= n) {
27
break;
28
} else {
29
countMoves++;
30
}
31
}
32

33
ans[i] = countMoves;
34
}
35
return ans;
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0