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: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because i

Python3

 1  1 class Solution:
 2  2     def judgeCircle(self, moves):
 3  3         """
 4  4         :type moves: str
 5  5         :rtype: bool
 6  6         """
 7  7         x = 0
 8  8         y = 0
 9  9         for s in moves:
10 10             if s == 'U':
11 11                 y += 1
12 12             elif s == 'D':
13 13                 y -= 1
14 14             elif s == 'R':
15 15                 x += 1
16 16             elif s == 'L':
17 17                 x -= 1
18 18         if (x, y) == (0, 0):
19 19             return True
20 20         else:
21 21             return False

猜你喜欢

转载自www.cnblogs.com/locke-hu/p/9628107.html