首页 > 其他分享 >leetcode 657. Judge Route Circle

leetcode 657. Judge Route Circle

时间:2023-05-30 18:03:39浏览次数:38  
标签:return Route move judgeCircle 657 Judge moves self out

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})

标签:return,Route,move,judgeCircle,657,Judge,moves,self,out
From: https://blog.51cto.com/u_11908275/6381159

相关文章

  • leetcode1657vector的初始化和比较
    满足相似的条件:1.长度一样2.组成的字母组合相同3.每个组成字母的个数集合相同比较两个vector,直接用==/!=排序vectorsort(迭代器1,迭代器2);初始化vector形式:vector<类型>name(形式)if(word1.lenth()!=word2.length())returnfalse;//长度不同vector<int>v2(26,0),v1(2......
  • vue this.$route.query 和this.$route.params的使用与区别
    一:this.$route.query的使用#1、传参数:this.$router.push({path:'/index/detail',query:{itemId:item.id}});#2、获取参数this.$route.query.itemId#3、url的表现形式http://localhost:8080/#/index/detail?itemId=22二:this.$route.params的使......
  • vue3学习中使用vue-router@4的问题Invalid VNode type: undefined (undefined)
    首先是按照常规的箭头函数引入的方法,结果报一下错误,且页面报错constHelloWorld=()=>import('../components/HelloWorld.vue'); 解决办法import{defineAsyncComponent}from'vue'constHelloWorld=defineAsyncComponent(()=>import('../components/HelloWorld.vue......
  • HUSTOJ特判程序Special Judge使用方法整理
    SpecialJudge通常的ACM题目包括以下几项内容:题目描述(Description)、输入描述(Input)、输出描述(Output)、样例输入(SampleInput)、样例输出(SampleOut),在后台则包括测试输入(InputData)和测试输出(OutputData)两项。在评测用户提交的程序正确与否时,系统会将样例输入和测试输......
  • 允许Traceroute探测漏洞修复
    vim/etc/sysconfig/iptables-AINPUT-picmp-micmp--icmp-typetime-exceeded-jDROP-AOUTPUT-picmp-micmp--icmp-typetime-exceeded-jDROP重启iptables服务:systemctlrestartiptables检查新添加的规则是否有效,检查命令:iptables-L-n......
  • IPQ8072 or IPQ8072A with the QCN9074/9024 chipset / well-suited for high-end rou
    TheIPQ8072andIPQ8072AarebothpowerfulnetworkingSoCs(System-on-Chip)designedbyQualcommforhigh-performancerouters,enterpriseWi-Fiaccesspoints,andothernetworkingequipment.ThesechipsarepartofQualcomm'sNetworkingProseriesan......
  • vue3 router 路由传参
    路由跳转importrouterfrom"@/router";router.push({path:"/iframe",query:{url:frameurl.value}});获取参数importrouterfrom"@/router";import{useRoute}from"vue-router";constroute=useRoute();const......
  • CodeForces 1827E Bus Routes
    洛谷传送门CF传送门比较神奇的题。定一个非叶子\(r\)为根。显然只用判断两个叶子是否可达。求出每个叶子向上能一步跳到的深度最浅的点\(p_i\),那么如果\(p_i\)不在一条链上就无解,因为两条路径没有交点。然后只用判断\(p_i\)最深的叶子的\(p_i\)能不能一步到达其他......
  • Pjudge #21680. 【PER #3】运算符 2
    一道很有教育意义的题目。首先我们有众所周知的AND卷积和XOR卷积,容易证明不同位互不干扰,拼起来可以获得\(1+4+5\)分的高分!接下来我们按照\(1\)的个数来讨论:\(0\)个\(1\):将这一位赋值为\(0\)即可。\(1\)个\(1\):如果形如0001那么就和AND卷积是一样的,那如果......
  • hdu-2680-Choose the best route(dijkstra)
    ChoosethebestrouteTimeLimit:2000/1000MS(Java/Others)    MemoryLimit:32768/32768K(Java/Others)TotalSubmission(s):10470    AcceptedSubmission(s):3367ProblemDescriptionOneday,Kikiwantstovisitoneofherfriends.Assheis......