【LeetCode】657. Judge Route Circle 解题报告
2018-01-13 15:46
447 查看
【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 日相关文章推荐
- [Leetcode] 657. Judge Route Circle 解题报告
- leetcode - 657. Judge Route Circle【向量思维 + 方向抵消(x,y)】
- LeetCode刷题 | 657. Judge Route Circle 水题
- leetcode 657. Judge Route Circle 环的判断
- LeetCode-657. Judge Route Circle
- Leetcode:657. Judge Route Circle (week 7)
- [Leetcode] 281. Zigzag Iterator 解题报告
- [leetcode]438. Find All Anagrams in a String@Java解题报告
- 【LeetCode】Integer to Roman 和 Roman to Integer 解题报告
- [leetcode] 371. Sum of Two Integers 解题报告
- [Leetcode] 468. Validate IP Address 解题报告
- 【LeetCode】320.Generalized Abbreviation(Medium)解题报告
- Divide Two Integers LeetCode 解题报告
- 【LeetCode】676. Implement Magic Dictionary 解题报告(Python)
- 【LeetCode】Unique Paths 解题报告
- LeetCode】66.Plus One(easy)解题报告
- [leetcode] 279. Perfect Squares 解题报告
- LeetCode 169. Majority Element 解题报告
- [leetcode] 111. Minimum Depth of Binary Tree 解题报告
- [Leetcode] 365. Water and Jug Problem 解题报告