forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1496.java
69 lines (63 loc) · 2.13 KB
/
_1496.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.fishercoder.solutions;
import java.util.Objects;
import java.util.Stack;
public class _1496 {
public static class Solution1 {
public boolean isPathCrossing(String path) {
Stack<Coord> visited = new Stack<>();
visited.add(new Coord(0, 0));
for (char c : path.toCharArray()) {
Coord last = visited.peek();
if (c == 'N') {
Coord nextStep = new Coord(last.x, last.y + 1);
if (visited.contains(nextStep)) {
return true;
}
visited.add(nextStep);
} else if (c == 'S') {
Coord nextStep = new Coord(last.x, last.y - 1);
if (visited.contains(nextStep)) {
return true;
}
visited.add(nextStep);
} else if (c == 'E') {
Coord nextStep = new Coord(last.x - 1, last.y);
if (visited.contains(nextStep)) {
return true;
}
visited.add(nextStep);
} else if (c == 'W') {
Coord nextStep = new Coord(last.x + 1, last.y);
if (visited.contains(nextStep)) {
return true;
}
visited.add(nextStep);
}
}
return false;
}
static class Coord {
int x;
int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Coord coord = (Coord) o;
return x == coord.x && y == coord.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
}