题目描述:输入一个字符串仅包括(WESN)表示前进方向,当走到曾经到过的地方就输出True,如果走完没有走到过之前的地方就输出False。
思路:把起始点当做xy坐标的(0,0)点,W为向X轴负方向前进,E为X轴正方向,S为Y轴负方向,N为Y轴正方向。接下来是判断当前节点是否走过:把每个节点的坐标都放在一个map中,key为X轴坐标;value为该X坐标对应走过的Y坐标,val可以用一个List或者set存放该x坐标所有对应的Y节点。每新到一个节点就可以检查是否走过该节点。
public class Num2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String path = in.next();
int x = 0;
int y = 0;
HashMap<Integer, LinkedList<Integer>> havePathMap = new HashMap<>();
LinkedList<Integer> beginList = new LinkedList<>();
beginList.add(0);
havePathMap.put(x, beginList);
boolean find = false;
for (int i = 0; i < path.length(); ++i){
if (path.charAt(i) == 'W')
x--;
if (path.charAt(i) == 'S')
y--;
if (path.charAt(i) == 'E')
x++;
if (path.charAt(i) == 'N')
y++;
if (havePathMap.containsKey(x)){
LinkedList<Integer> tempList = havePathMap.get(x);
for (int j = 0; j < tempList.size(); ++j){
if (y == tempList.get(j)){
find = true;
System.out.println("True");
break;
}
}
if (find)
break;
else
havePathMap.get(x).add(y);
}else {
LinkedList<Integer> tempList = new LinkedList<>();
tempList.add(y);
havePathMap.put(x,tempList);
}
}
if (!find)
System.out.println("False");
}
}
优化:把存放y节点的list换成Set,提升效率。把四个if和下面的if都可以单独拿出来写成一个方法,增加可读性。