-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJudgingWhetherThePathsIntersect.java
63 lines (56 loc) · 1.55 KB
/
JudgingWhetherThePathsIntersect.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
package other;
import java.util.HashSet;
import java.util.Set;
/**
* @Author: Wenhang Chen
* @Description:给你一个字符串 path,其中 path[i] 的值可以是 'N'、'S'、'E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。
*
* 机器人从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。
*
* 如果路径在任何位置上出现相交的情况,也就是走到之前已经走过的位置,请返回 True ;否则,返回 False 。
*
*
*
* 示例 1:
*
*
*
* 输入:path = "NES"
* 输出:false
* 解释:该路径没有在任何位置相交。
* 示例 2:
*
*
*
* 输入:path = "NESWW"
* 输出:true
* 解释:该路径经过原点两次。
*
* @Date: Created in 20:59 8/2/2020
* @Modified by:
*/
public class JudgingWhetherThePathsIntersect {
public boolean isPathCrossing(String path) {
Set<Integer> vis = new HashSet<Integer>();
int x = 0, y = 0;
vis.add(getHash(x, y));
int length = path.length();
for (int i = 0; i < length; i++) {
char dir = path.charAt(i);
switch (dir) {
case 'N': --x; break;
case 'S': ++x; break;
case 'W': --y; break;
case 'E': ++y; break;
}
int hashValue = getHash(x, y);
if (!vis.add(hashValue)) {
return true;
}
}
return false;
}
public int getHash(int x, int y) {
return x * 20001 + y;
}
}