LeetCode-657. Robot Return to Origin

网友投稿 251 2022-08-29

LeetCode-657. Robot Return to Origin

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: "UD"Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: "LL"Output: falseExplanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

题解:

class Solution {public: bool judgeCircle(string moves) { int n = moves.size(); int x = 0, y = 0; for (int i = 0; i < n; i++) { if (moves[i] == 'U') { y++; } if (moves[i] == 'D') { y--; } if (moves[i] == 'R') { x++; } if (moves[i] == 'L') { x--; } } if (x == 0 && y == 0) { return true; } return false; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:完美日记,被自己的营销神话打败!(完美日记成功营销)
下一篇:LeetCode-145. Binary Tree Postorder Traversal
相关文章

 发表评论

暂时没有评论,来抢沙发吧~