LeetCode 题解工作台

判断路径是否相交

给你一个字符串 path ,其中 path[i] 的值可以是 'N' 、 'S' 、 'E' 或者 'W' ,分别表示向北、向南、向东、向西移动一个单位。 你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。 如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以用一个哈希表 记录路径上的点。初始时 中只有原点 $(0, 0)$。 遍历字符串 ,对于每个字符 ,根据 的值更新当前位置 $(i, j)$,然后判断 $(i, j)$ 是否在 中,如果在,则返回 `true`,否则将 $(i, j)$ 加入 中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 path,其中 path[i] 的值可以是 'N''S''E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。

你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。

如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false

 

示例 1:

输入:path = "NES"
输出:false 
解释:该路径没有在任何位置相交。

示例 2:

输入:path = "NESWW"
输出:true
解释:该路径经过原点两次。

 

提示:

  • 1 <= path.length <= 104
  • path[i]'N''S''E''W'
lightbulb

解题思路

方法一:哈希表

我们可以用一个哈希表 visvis 记录路径上的点。初始时 visvis 中只有原点 (0,0)(0, 0)

遍历字符串 pathpath,对于每个字符 cc,根据 cc 的值更新当前位置 (i,j)(i, j),然后判断 (i,j)(i, j) 是否在 visvis 中,如果在,则返回 true,否则将 (i,j)(i, j) 加入 visvis 中。

遍历结束后,返回 false

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 pathpath 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def isPathCrossing(self, path: str) -> bool:
        i = j = 0
        vis = {(0, 0)}
        for c in path:
            match c:
                case 'N':
                    i -= 1
                case 'S':
                    i += 1
                case 'E':
                    j += 1
                case 'W':
                    j -= 1
            if (i, j) in vis:
                return True
            vis.add((i, j))
        return False
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to recognize the importance of hashing for tracking visited points in path problems.

  • question_mark

    Effective use of hash tables for fast lookups to detect repeated points.

  • question_mark

    Clear understanding of the simulation pattern and its relation to path traversal problems.

warning

常见陷阱

外企场景
  • error

    Failing to track the starting point (0, 0) as a visited location can lead to incorrect results.

  • error

    Using inefficient data structures like arrays instead of hash tables, leading to slower performance for large inputs.

  • error

    Not handling edge cases like very short paths (e.g., paths of length 1) or paths with only one direction.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the path involves diagonal moves, not just N, S, E, W?

  • arrow_right_alt

    How would the solution change if the plane was 3D instead of 2D?

  • arrow_right_alt

    What if the path has obstacles that block movement, and you need to account for those?

help

常见问题

外企场景

判断路径是否相交题解:哈希·表·结合·string | LeetCode #1496 简单