leetcode Daily Challenge on September 17th, 2020.
Difficulty : Medium
Related Topics : Math
On an infinite plane, a robot initially stands at
(0, 0)
and faces north. The robot can receive one of three instructions:
- '"G"': go straight 1 unit;
- '"L"': turn 90 degrees to the left;
- '"R"': turn 90 degress to the right.
The robot performs the
instructions
given in order, and repeats them forever.Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Input: "GG" Output: false Explanation: The robot moves north indefinitely.
Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
1 <= instructions.length <= 100
instructions[i]
is in {'G', 'L', 'R'
}
- mine
- Java
Runtime: 9 ms, faster than 5.22%, Memory Usage: 39.9 MB, less than 5.16% of Java online submissions
// O(N)time // O(N)space public boolean isRobotBounded(String ins) { int[][] dir = new int[4][2]; dir[0] = new int[]{1,0}; dir[1] = new int[]{0,-1}; dir[2] = new int[]{-1,0}; dir[3] = new int[]{0,1}; int s = 3; int x = 0, y = 0; int i = 0; char[] arr = ins.toCharArray(); Set<String> set = new HashSet<>(); set.add("0-0"); while(i < 4){ i++; for(char c : arr){ if(c == 'G'){ x += dir[s][0]; y += dir[s][1]; }else if(c == 'L'){ s = (s + 3) % 4; }else{ s = (s + 1) % 4; } } String t = x + "-" + y; if(set.contains(t)){ return true; }else{ set.add(t); } } return false; }
- Java
- the most votes
Runtime: 1 ms, faster than 34.44%, Memory Usage: 39.1 MB, less than 13.97% of Java online submissions
// O(N)time // O(1)space public boolean isRobotBounded(String ins) { int x = 0, y = 0, i = 0, d[][] = {{0, 1}, {1, 0}, {0, -1}, { -1, 0}}; for (int j = 0; j < ins.length(); ++j) if (ins.charAt(j) == 'R') i = (i + 1) % 4; else if (ins.charAt(j) == 'L') i = (i + 3) % 4; else { x += d[i][0]; y += d[i][1]; } return x == 0 && y == 0 || i > 0; }