leetcode(6) JudgeRouteCircle

difficult:easy #657
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:

1
2
Input: "UD"
Output: true

Example 2:
1
2
Input: "LL"
Output: false

解法一:
1
2
3
4
5
6
7
8
9
#include<string>
#include<map>
bool judgeCircle(std::string moves) {
std::map<char, int> action = { {'R',0},{'L',0},{'U',0},{'D',0} };
for (int i = 0; i < moves.size(); i++) {
action[moves[i]]++;
}
return action['R'] == action['L'] && action['U'] == action['D'];
}

解法二:
1
2
3
4
5
6
7
8
9
10
11
12
#include<string>
#include<map>
bool judgeCircle(std::string moves) {
int x = 0, y = 0;
for (char move:moves) {
if (move == 'U') y--;
else if (move == 'D') y++;
else if (move == 'R') x--;
else if (move == 'L') x++;
}
return x == 0 && y == 0;
}

版权声明:原创,转载请注明来源,否则律师函警告


leetcode(6) JudgeRouteCircle
https://jiaopaner.github.io/2018/07/11/leetcode(6) JudgeRouteCircle/
作者
JiaoPan
发布于
2018年7月11日
许可协议