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
Example 2:
Input: "LL" Output: false
这道题是判断一个路径是否绕圈,也就是U和D,L和R的个数要求相等。可以使用两个计数器,如果是U,则cnt1自增1;如果是D,cnt1自减1。同理,如果是L,则cnt1自增1;如果是R,cnt1自减1。最后只要看cnt1和cnt2是否同时为0。
class Solution {
public:
bool judgeCircle(string moves) {
int cnt1 = 0, cnt2 = 0;
for (char move : moves) {
if (move == 'U') ++cnt1;
else if (move == 'D') --cnt1;
else if (move == 'L') ++cnt2;
else if (move == 'R') --cnt2;
}
return cnt1 == 0 && cnt2 == 0;
}
};