1. 程式人生 > >657. Judge Route Circle

657. Judge Route Circle

whether 輸出 this 思想 osi 停止 字符串 class turn

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

657. Judge Route Circle