leetcode 657. Judge Route Circle
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
解法1:
class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool out("")=True out("L" or "D" or "U" or "R") =False out("LR")=True out("RL")=True out("RLDU")=True out("LLR")=False """ x = y = 0 for m in moves: if m == "L": x -= 1 elif m == "R": x += 1 elif m == "U": y += 1 else: y -= 1 return x==0 and y==0
用查找表更好:
class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ x,y = 0,0 offsets = {"U":[0,1], "D":[0,-1], "R":[1,0], "L":[-1,0]} for move in moves: x,y = x+offsets[move][0], y+offsets[move][1] return (x == 0) and (y == 0)
解法2:
def judgeCircle(self, moves): return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
直接统计LR数目是否相等,同时UD数目是否相等。
类似代码:
def judgeCircle(self, moves): c = collections.Counter(moves) return c['L'] == c['R'] and c['U'] == c['D']
因为:
>>> import collections
>>> collections.Counter("abca")
Counter({'a': 2, 'b': 1, 'c': 1})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-02-27 linkedin databus介绍——监听数据库变化,有新数据到来时通知其他消费者app,新数据存在内存里,多份快照
2017-02-27 ES忽略TF-IDF评分——使用constant_score
2017-02-27 ES设置字段搜索权重——Query-Time Boosting
2017-02-27 lucene内置的评分函数
2017-02-27 ES搜索排序,文档相关度评分介绍——Vector Space Model
2017-02-27 ES搜索排序,文档相关度评分介绍——TF-IDF—term frequency, inverse document frequency, and field-length norm—are calculated and stored at index time.
2017-02-27 ES搜索排序,文档相关度评分介绍——Field-length norm