[leetcode] 1496. Path Crossing

网友投稿 901 2022-10-01

[leetcode] 1496. Path Crossing

[leetcode] 1496. Path Crossing

Description

Given a string path, where path[i] = ‘N’, ‘S’, ‘E’ or ‘W’, each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.

Return True if the path crosses itself at any point, that is, if at any time you are on a location you’ve previously visited. Return False otherwise.

Example 1:

Input: path = "NES"Output: false Explanation: Notice that the path doesn't cross any point more than once.

Example 2:

Input: path = "NESWW"Output: trueExplanation: Notice that the path visits the origin twice.

Constraints:

1 <= path.length <= 10^4path will only consist of characters in {‘N’, ‘S’, ‘E’, 'W}

分析

题目的意思是:给定一个字符串表示点的移动方向,判断这个点的轨迹是否交叉。我看了一下提示,思路大概是这样,用points记录点走过的坐标,然后遍历判断当前的坐标是否在points里面就行了,如果是则找到了,返回True,否则返回False。

代码

class Solution: def isPathCrossing(self, path: str) -> bool: x=0 y=0 points=[[0,0]] for ch in path: if(ch=='N'): y+=1 elif(ch=='S'): y-=1 elif(ch=='E'): x+=1 elif(ch=='W'): x-=1 if([x,y] in points): return True else: points.append([x,y]) return False

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序不能用怎么办(微信里小程序不能用怎么回事)
下一篇:小程序scoll-view用法注意事项(小程序 scroll-view)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~