leetcode 1496. Path Crossing(python)

这篇博客讲解如何利用Python解决一个路径问题,即给定由'N','S','E','W'指示的移动路径,判断路径是否在某个点交叉。核心在于跟踪每一步的位置变化,若遇到重复位置则返回True,否则False。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

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.

原题链接:https://leetcode.com/problems/path-crossing/

您的支持是我最大的动力

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值