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:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
解法一:
#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'];
}
解法二:
#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;
}
版权声明:原创,转载请注明来源,否则律师函警告
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!