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:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

最初,位置(0,0)处有一个机器人。给出它的一系列动作,判断这个机器人是否有一个圆圈,这意味着它回到原来的位置移动顺序由一个字符串表示。而每一个动作都是由一个人物来表现的。有效的机器人移动的R(右)L(左), U(上)和D(下)。输出应该是真或假,表示机器人是否成圈。

例1:

输入: “UD”
 输出:

例2:

输入: “LL”
 输出:错误

(1)思想1:因为只有水平和垂直的两个方向,所以用两个计数con1和con2,初始为0,con1记录垂直方向,当UP的时候,con1++,当DOWN的时候,con1--;con2记录水平方向,当Right的时候,con2++,当Left的时候,con2--;最终停止的时候,判断con1和con2是否同时为0,同时为0则在原点,否则不在。

C++代码如下:

 1 class Solution {
 2 public:
 3     bool judgeCircle(string moves) {
 4         int con1=0;
 5         int con2=0;
 6         for(char c : moves)
 7         {
 8             if(c=='U')
 9                 con1++;
10             else if(c=='D')
11                 con1--;
12             else if(c=='R')
13                 con2++;
14             else
15                 con2--;
16         }
17         if(con1==0 and con2==0)
18             return true;
19         else
20             return false;
21     }
22 };

 Python代码:

 1 class Solution:
 2     def judgeCircle(self, moves):
 3         con1=0
 4         con2=0
 5         for c in moves:
 6             if c=='U':
 7                 con1=con1+1
 8             elif c=='D':
 9                 con1=con1-1
10             elif c=='R':
11                 con2=con2+1
12             elif c=='L':
13                 con2=con2-1
14         if con1==0 and con2==0:
15             return True
16         else:
17             return False
原文地址:https://www.cnblogs.com/sword-/p/8029840.html