给你一个字符串 path,其中 path[i] 的值可以是 'N'、'S'、'E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。
你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。
如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false 。
可以使用一个HashSet来记录走过的位置,判断当前位置是否已经走过。遍历字符串 path 中的每个字符,根据字符指示的方向更新当前位置,并将当前位置加入HashSet。如果HashSet中已经包含当前位置,说明路径与自身相交,返回true。如果遍历完字符串后都没有相交的情况发生,返回false。
import java.util.HashSet; public class Solution { public boolean isPathCrossing(String path) { int x = 0, y = 0; // 初始位置为(0, 0) HashSet<String> visited = new HashSet<>(); // 用HashSet记录走过的位置 visited.add("0,0"); // 将初始位置加入HashSet for (char direction : path.toCharArray()) { if (direction == 'N') { y++; // 向北移动 } else if (direction == 'S') { y--; // 向南移动 } else if (direction == 'E') { x++; // 向东移动 } else if (direction == 'W') { x--; // 向西移动 } String currentPosition = x + "," + y; // 当前位置的坐标 // 如果HashSet中已经包含当前位置,说明路径与自身相交,返回true if (visited.contains(currentPosition)) { return true; } // 将当前位置加入HashSet visited.add(currentPosition); } // 遍历完路径后都没有相交的情况发生,返回false return false; } }