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 represented 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
Example 2:
Input: "LL" Output: false
这个题很简单,就是判断各种拐弯时候能不能绕回来。 直接上代码吧。
class Solution {
public:
bool judgeCircle(string moves) {
if (moves.length() == 0) return true;
if (moves.length() % 2 == 1) return false;
int offset_x = 0;
int offset_y = 0;
for (int i = 0; i < moves.length(); i++) {
if (moves[i] == 'U') {
offset_y++;
} else if (moves[i] == 'D') {
offset_y--;
} else if (moves[i] == 'L') {
offset_x--;
} else if (moves[i] == 'R') {
offset_x++;
} else {
i++;
}
}
return offset_x == 0 && offset_y == 0 ? true : false;
}
};