# 【LeetCode】657. Robot Return to Origin 解题报告（Python）

LeetCode 同时被 2 个专栏收录
892 篇文章 64 订阅
1022 篇文章 9 订阅

id： fuxuemingzhu

## 题目描述

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 it is not at the origin at the end of its moves.


## 解题方法

### 复数求和

Python支持复数运算的，所以指定不同的方向是不同的实数数字就行了。复数的标记是j。最后求和判断是不是0就是到了原点。

class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
directs = {'L':-1, 'R':1, 'U':1j, 'D':-1j}
return 0 == sum(directs[move] for move in moves)


### counter统计次数

class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
count = collections.Counter(moves)
return count['U'] == count['D'] and count['L'] == count['R']


class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
u = d = l = r = 0
for move in moves:
if move == 'U':
u += 1
elif move == "D":
d += 1
elif move == 'L':
l += 1
elif move == 'R':
r += 1
return u == d and l == r


## 日期

2018 年 11 月 2 日 —— 浑浑噩噩的一天

• 0
点赞
• 2
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

05-28 112
09-07 930
09-08 363
08-15 1418
©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。