leetcode 1496. Path Crossing(python)

651 阅读1分钟

描述

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:

avatar

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

Example 2:

avatar

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

Note:

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

解析

根据题意,就是如果点根据方向移动的位置又回到了以前走过的位置则返回 True ,否则返回 False 。思路简单,就是用列表将每个点的位置都记录下来,只要之后移动的位置也在列表中存在就返回 True ,否则将该位置加入到列表中,循环这个步骤,直到结束。

解答

class Solution(object):
    def isPathCrossing(self, path):
        """
        :type path: str
        :rtype: bool
        """
        points = [(0, 0)]
        for c in path:
            point = None
            if c == 'N':
                point = (points[-1][0], points[-1][1] + 1)
            elif c == 'S':
                point = (points[-1][0], points[-1][1] - 1)
            elif c == 'E':
                point = (points[-1][0] + 1, points[-1][1])
            elif c == 'W':
                point = (points[-1][0] - 1, points[-1][1])
            if point not in points:
                points.append(point)
            else:
                return True
        return False            	      
		

运行结果

Runtime: 8 ms, faster than 100.00% of Python online submissions for Path Crossing.
Memory Usage: 13.8 MB, less than 30.63% of Python online submissions for Path Crossing.

原题链接:leetcode.com/problems/pa…

您的支持是我最大的动力