Robot Bounded In Circle

这个是当年google的杀人题。当时砍了好多人下去,上来想优化的全死了,其实就是按照题意做一个tracking方向和最后的位置点。这个题最难的是用什么来实现模拟行走,贴个不错的网友答案

class Solution {
    public boolean isRobotBounded(String instructions) {
        int x = 0; // 横轴位置
        int y = 0; //竖轴位置
        int i = 0; //朝向, 0=n,1=e,2=s,3=w
        int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 上面的i对应这里的方位
        for (char c : instructions.toCharArray()) {
            if (c == 'R') {
                i = (i + 1) % 4;
            } else if (c == 'L') {
                i = (i + 3) % 4;
            } else {
                x += direction[i][0];
                y += direction[i][1];
            }
        }
        return x == 0 && y == 0 || i > 0;
    } 
}