1496. Path Crossing
作者:互联网
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
.
Return True
if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False
otherwise.
Example 1:
Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more than once.
Example 2:
Input: path = "NESWW" Output: true Explanation: Notice that the path visits the origin twice.
Constraints:
1 <= path.length <= 10^4
path
will only consist of characters in{'N', 'S', 'E', 'W}
class Solution { public boolean isPathCrossing(String path) { List<Integer> pos = Arrays.asList(0,0); Set<List<Integer>> set = new HashSet(); set.add(pos); // boolean cross = false; // System.out.println(pos.get(0) + " " + pos.get(1)); for(char c: path.toCharArray()){ int hor = pos.get(1); int ver = pos.get(0); if(c == 'N'){ ver++; } else if(c == 'S'){ ver--; } else if(c == 'E'){ hor++; } else hor--; // pos = ; //System.out.println(pos[0] + " " + pos[1]); pos = Arrays.asList(ver, hor); // System.out.println(pos.get(0) + " " + pos.get(1)); if(set.contains(pos)) return true; else set.add(pos); } return false; } }
simulation,起始是0,0,把途径的点表示成arraylist加入set中看有没有重复
注意不能用array,因为就算两个数组元素相等,只要不是同1 reference也会判定不相等,而List的比较是也比较element。
class Solution { public boolean isPathCrossing(String path) { int x = 0, y = 0; Set<String> set = new HashSet(); set.add(x + "$" + y); for (char c : path.toCharArray()) { if (c == 'N') y++; else if (c == 'S') y--; else if (c == 'E') x++; else x--; String key = x + "$" + y; if (set.contains(key)) return true; set.add(key); } return false; } }
像这种表示就更简单了,忘球了可惜,以前在哪里见过来着
标签:set,ver,get,pos,else,1496,path,Crossing,Path 来源: https://www.cnblogs.com/wentiliangkaihua/p/13210926.html