【題目】5448. 判斷路徑是否相交
給你一個字符串 path,其中 path[i] 的值可以是 ‘N’、‘S’、‘E’ 或者 ‘W’,分別表示向北、向南、向東、向西移動一個單位。
機器人從二維平面上的原點 (0, 0) 處開始出發,按 path 所指示的路徑行走。
如果路徑在任何位置上出現相交的情況,也就是走到之前已經走過的位置,請返回 True ;否則,返回 False 。
示例 1:
輸入:path = "NES"
輸出:false
解釋:該路徑沒有在任何位置相交。
示例 2:
輸入:path = "NESWW"
輸出:true
解釋:該路徑經過原點兩次。
提示:
1 <= path.length <= 10^4
path 僅由 {‘N’, ‘S’, ‘E’, 'W} 中的字符組成
【解題思路1】Set,將座標轉化爲string存
set是容易想到的,但是不能存儲鍵值對,而map又會覆蓋value,所以存字符串模擬座標。
class Solution {
public boolean isPathCrossing(String path) {
int x=0;
int y=0;
Set<String> set=new HashSet<>();
set.add("0,0");
for(int k=0;k<path.length();k++){
char c=path.charAt(k);
if(c=='N')y++;
if(c=='S')y--;
if(c=='E')x++;
if(c=='W')x--;
String temp=x+","+y;
if(set.contains(temp)){
return true;
}else{
set.add(temp);
}
}
return false;
}
}
【解題思路2】Set<Pair<Integer, Integer>>
class Solution {
public boolean isPathCrossing(String path) {
Set<Pair<Integer, Integer>> set = new HashSet<>();
int x = 0, y = 0;
set.add(new Pair(x, y));
for (char c: path.toCharArray()) {
switch (c) {
case 'N':
y++;
break;
case 'S':
y--;
break;
case 'E':
x++;
break;
case 'W':
x--;
break;
}
Pair pair = new Pair(x, y);
if (set.contains(pair))
return true;
set.add(pair);
}
return false;
}
}