题目链接:
https://leetcode.com/problems/judge-route-circle/description/
题目描述:
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.
题解:用x和y表示机器人的坐标,上下左右的移动后的位置转化为横坐标和纵坐标的值,最后判断坐标值是否为(0,0)
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0;
int y = 0;
for (int i = 0; i < moves.length(); i++) {
switch(moves[i]) {
case 'U':
y++;
break;
case 'D':
y--;
break;
case 'L':
x--;
break;
case 'R':
x++;
break;
default: break;
}
}
return ((x == 0) && (y == 0));
}
};