05 August 2008
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
(Right), 1
R
(Left), 1
L
(Up) and 1
U
(down). The output should be true or false representing whether the robot makes a circle.1
D
Example 1:
1
2
Input: "UD"
Output: true
Example 2:
1
2
Input: "LL"
Output: false
找是否绕圈,有多少个U就得有多少个D,有多少个L就得有多少个R,跟20 - Valid Parentheses类似,那道题用stack来解,这个题更简单,两个计数器来看最后是否为0就行了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public boolean judgeCircle(String moves) {
if (moves == null || moves.length() == 0) {
return true;
}
int countH = 0, countV = 0;
for (int i = 0; i < moves.length(); i++) {
if (moves.charAt(i) == 'L') countH++;
if (moves.charAt(i) == 'R') countH--;
if (moves.charAt(i) == 'U') countV++;
if (moves.charAt(i) == 'D') countV--;
}
return countH == 0 && countV == 0;
}
}