问题
一个人被告知去一个地方怎么走:方向是”NORTH”, “SOUTH”, “WEST”, “EAST”,显然先NORTH再SOUTH等于没走,先WEST再EAST也是没走。这个路径简化后就是个“”;
现在给出一个路径,要求将其简化。注意,只简化相连的两个方向。
例子
assertEquals("\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"",
new String[]{"WEST"},
DirReduction.dirReduc(new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"}));
assertEquals("\"NORTH\", \"WEST\", \"SOUTH\", \"EAST\"",
new String[]{"NORTH", "WEST", "SOUTH", "EAST"},
DirReduction.dirReduc(new String[]{"NORTH", "WEST", "SOUTH", "EAST"}));
我的代码
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class DirReduction {
public static HashMap<String, String> map = new HashMap<String, String>();
public static String[] dirReduc(String[] arr) {
map.put("NORTH","SOUTH");
map.put("WEST","EAST");
map.put("SOUTH","NORTH");
map.put("EAST","WEST");
int position = 0;
List<String> list = new LinkedList<>();
for (String str : arr) {
if (position == 0 || !iSReverse(list.get(position-1), str)) {
list.add(str);
position++;
continue;
} else {
list.remove(position-1);
position--;
}
}
return list.toArray(new String[list.size()]);
}
public static boolean iSReverse(String oldStr, String newStr) {
return oldStr.equals(map.get(newStr))? true : false;
}
public static void main(String[] args) {
String[] result = DirReduction.dirReduc(new String[]{"NORTH", "WEST", "SOUTH", "EAST"});
System.out.println(result);
}
}
高手的代码
import java.util.Stack;
public class DirReduction {
public static String[] dirReduc(String[] arr) {
final Stack<String> stack = new Stack<>();
for (final String direction : arr) {
final String lastElement = stack.size() > 0 ? stack.lastElement() : null;
switch(direction) {
case "NORTH": if ("SOUTH".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
case "SOUTH": if ("NORTH".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
case "EAST": if ("WEST".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
case "WEST": if ("EAST".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
}
}
return stack.stream().toArray(String[]::new);
}
}
分析
这道题本质上是一道出栈和入栈的实现问题。高手代码的一个值得学习的地方是用到的Stack这个实现栈功能的类,比我的代码高明,不需要维护一个位置指针。