GuoXin Li's Blog

LeetCode 657 Judge Route Cricle 机器人是否返回原点

字数统计: 332阅读时长: 2 min
2020/02/16 Share

Judge Route Circle 机器人是否返回原点

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: “UD”
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: “LL”
Output: false
Explanation: The robot moves left twice. It ends up two “moves” to the left of the origin. We return false because it is not at the origin at the end of its moves.

Resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//C++
class Solution {
public:
bool judgeCircle(string moves) {
int hori = 0, vert = 0;
for (const char move : moves){
switch(move){
case 'U':
++vert;
break;
case 'D':
--vert;
break;
case 'L':
--hori;
break;
case 'R':
++hori;
break;
}
}
return hori == 0 && vert == 0;
}
};

Time Complexity: $O(N)$

Space Complexity: $O(1)$

learning note:

In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the evolution of the language over the years:

  • First one, C-like Initialization

    1
    int x = 0;
  • type identifier (initial_value)

    1
    int x(0);
  • this was introduced by the revision of the C++ standard, in 2011

    1
    int x{0};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Java
class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for ( char move : moves.toCharArray() ){
switch(move){
case 'U':
++y;
break;
case 'D':
--y;
break;
case 'R':
++x;
break;
case 'L':
--x;
break;
default:
return false;
}
}
return x == 0 && y == 0;
}
}
CATALOG
  1. 1. Judge Route Circle 机器人是否返回原点
    1. 1.1. Example 1:
    2. 1.2. Example 2:
    3. 1.3. Resolution