657. Robot Return to Origin

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
``````

``````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;
}
};
``````

``````class Solution {
public:
bool judgeCircle(string moves) {
unordered_map<char, int> m;
for (char c : moves) ++m[c];
return m['L'] == m['R'] && m['U'] == m['D'];
}
};
``````

Valid Parentheses

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation