【LeetCode】657. Judge Route Circle

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/judge-route-circle/description/

题目描述:

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:
Input: “UD”
Output: true
Example 2:
Input: “LL”
Output: false

Ways

python里面表达坐标比较简单,直接用列表就可以。

这个题就是判断移动了几次之后是否在原来的位置,只要每步都去修改一次即可。

方法一,O(n):

class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
position = [0, 0]
for move in moves:
if move == 'R':
position[0] += 1
if move == 'L':
position[0] -= 1
if move == 'U':
position[1] += 1
if move == 'D':
position[1] -= 1
return position == [0, 0]

方法二,数左右移动的次数和上下移动的次数是否相等:

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

方法三,看了Discuss才知道,python原来也可以用复数!

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)

Date

2018 年 1 月 13 日

最新文章

  1. Web 前端开发精华文章推荐(jQuery、HTML5、CSS3)【系列十二】
  2. Linux(Ubuntu 14.04) setting up OpenGL
  3. class.equals
  4. ural 1338. Automobiles
  5. 【oracle】解锁oracle用户,unlock
  6. css整个页面离顶部的距离
  7. 二模07day2解题报告
  8. php.ini的配置
  9. 新浪实时股票数据接口http://hq.sinajs.cn/list=code
  10. poj 3250 Bad Hair Day (单调栈)
  11. 源泉书签,助您管理海量收藏。www.yuanquanshuqian.com,今日更新:多标签功能已实现
  12. MySQL的数据类型,MySQL增删改--添加主外键、添加属性、删除主外键、改表名、获取系统当前时间等
  13. PAT乙级1004. 成绩排名 (20)
  14. 笔记:Struts2 输入校验
  15. 微信小程序常见的坑
  16. Bellman-Ford算法(在边权可正可负时求最短路)
  17. mysql库、表、索引
  18. 双机热备(准)-->RAC(夭折)-->DG(异地容灾)
  19. 获取bean的两种方式
  20. brendangregg

热门文章

  1. R语言与医学统计图形-【18】ggplot2几何对象汇总
  2. python 多行对应元素求和
  3. git放弃修改,强制覆盖本地代码
  4. 8.Maximum Depth of Binary Tree
  5. C/C++ Qt StandardItemModel 数据模型应用
  6. Yarn 容量调度器多队列提交案例
  7. Yarn 生产环境核心参数配置案例
  8. A Child's History of England.21
  9. 12. Fedora 中文乱码问题
  10. Angular中@Output()的使用方法