LC.P1041[困于环中的机器人]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public boolean isRobotBounded(String instructions) {
int[] dist = new int[4];
int k = 0;
for (int i = 0; i < instructions.length(); ++i) {
char c = instructions.charAt(i);
if (c == 'L') k = (k + 1) % 4;
else if (c == 'R') k = (k + 3) % 4;
else ++dist[k];
}
return (k != 0) || (dist[0] == dist[2] && dist[1] == dist[3]);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$