Skip to content

Commit 274477b

Browse files
committed
feat: solve No.1496
1 parent bff2d2c commit 274477b

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

1401-1500/1496. Path Crossing.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# 1496. Path Crossing
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Hash Table, String.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
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`.
10+
11+
Return `true` **if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited**. Return `false` otherwise.
12+
13+
 
14+
Example 1:
15+
16+
![](https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123929-pm.png)
17+
18+
```
19+
Input: path = "NES"
20+
Output: false
21+
Explanation: Notice that the path doesn't cross any point more than once.
22+
```
23+
24+
Example 2:
25+
26+
![](https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123843-pm.png)
27+
28+
```
29+
Input: path = "NESWW"
30+
Output: true
31+
Explanation: Notice that the path visits the origin twice.
32+
```
33+
34+
 
35+
**Constraints:**
36+
37+
38+
39+
- `1 <= path.length <= 104`
40+
41+
- `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`.
42+
43+
44+
45+
## Solution
46+
47+
```javascript
48+
/**
49+
* @param {string} path
50+
* @return {boolean}
51+
*/
52+
var isPathCrossing = function(path) {
53+
var num = 0;
54+
var map = {
55+
N: 1,
56+
S: -1,
57+
E: 10000,
58+
W: -10000,
59+
};
60+
var visited = { '0': true };
61+
for (var i = 0; i < path.length; i++) {
62+
num += map[path[i]];
63+
if (visited[num]) return true;
64+
visited[num] = true;
65+
}
66+
return false;
67+
};
68+
```
69+
70+
**Explain:**
71+
72+
nope.
73+
74+
**Complexity:**
75+
76+
* Time complexity : O(n).
77+
* Space complexity : O(n).

0 commit comments

Comments
 (0)