-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPathCrossing.java
44 lines (38 loc) · 1.1 KB
/
PathCrossing.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
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.*;
// https://leetcode.com/problems/path-crossing/
public class PathCrossing {
private final String path;
public PathCrossing(String input) {
this.path = input;
}
public boolean solution() {
Map<Integer, Set<Integer>> store = new HashMap<>();
store.put(0, new HashSet<>(List.of(0)));
for (int i = 0, a = 0, b = 0; i < path.length(); i++) {
char moveUnit = path.charAt(i);
switch (moveUnit) {
case 'N':
a++;
break;
case 'S':
a--;
break;
case 'E':
b++;
break;
case 'W':
b--;
break;
}
var set = store.getOrDefault(a, new HashSet<>());
if (set.contains(b)) {
return true;
} else {
set.add(b);
store.put(a, set);
}
}
return false;
}
}