Problem:
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 |
Idea:
Simulation
Solution:
C++
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 |
// Author: Huahua // Runtime: 19 ms class Solution { public: bool judgeCircle(string moves) { int cx{0}; int cy{0}; for (const char move : moves) { switch(move) { case 'U': cy--; break; case 'D': cy++; break; case 'R': cx++; break; case 'L': cx--; break; } } return cx==0 && cy==0; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment