清风的技术小屋

不为所动, 做更专业的自己

0%

LeetCode 657 - Judge Route Circle

问题描述

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

Related Topics: String

原问题: 657. Judge Route Circle

中文翻译版: 657. 判断路线成圈

解决方案

根据题目描述,可以设定一个二维坐标 (x, y),根据指令做相应的改变:

  • Right: x = x + 1
  • Left: x = x - 1
  • Up: y = y + 1
  • Down: y = y - 1

最后判断二维坐标 (x, y) 是否为原点 (0, 0) 即可。实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;

class Solution {
public:
bool judgeCircle(string moves)
{
int x = 0, y = 0;

for (int i=0; i<moves.size(); i++) {
switch (moves[i]) {
case 'U':
y++;
break;
case 'D':
y--;
break;
case 'L':
x--;
break;
case 'R':
x++;
break;
}
}

return (x == 0 && y == 0);
}
};

int main()
{
Solution solu;
string str1 = "UD";
cout << str1 << ": " << solu.judgeCircle(str1) << endl;
string str2 = "LL";
cout << str2 << ": " << solu.judgeCircle(str2) << endl;

return 0;
}