Judge Route Circle --判斷圓路線
阿新 • • 發佈:2017-10-28
ive move else class down out posit pre false (down). The output should be true or false representing whether the robot makes a 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
Example 1:
Input: "UD" Output: true
Example 2:
Input: "LL" Output: false
思路:
1.這是一個模擬橫縱坐標移動的問題,向左移動x--,向右x++,向上y++,向下y--,最後判斷 x == 0 && y == 0即可。
2.直接判斷‘L‘,‘R‘,‘U‘,‘D‘出現的次數是否相等
實現代碼:
class Solution {public: bool judgeCircle(string moves) { int x=0,y=0; for (int i = 0; i < moves.length(); i++){ if (moves[i] == ‘L‘) x--; else if (moves[i] == ‘R‘) x++; else if (moves[i] == ‘U‘) y++; else y--; } returnx == 0 && y == 0; } };
Judge Route Circle --判斷圓路線