自己写的短路
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class shortestWay {
public static void main(String[] args) {
// TODO Auto-generated method stub
String regex="[nNsSwWeE][nNsSwWeE]*";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inWay = null;
boolean errFlag = false;
int cntX = 0;
int cntY = 0;
byte[] byteWay = null;
char[] byteWays = null;
StringBuilder shortestWay = new StringBuilder();
while ((inWay == null) || ("".equals(inWay.trim())) || inWay.length() > 50 || errFlag) {
System.out.print("input the way: ");
try {
inWay = br.readLine();
if (inWay.length() > 50)
System.out.println("wrong way length");
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(inWay);
if(m.matches()){
errFlag = false;
System.out.println("you just input the way is :" + m.group());
}else{
errFlag = true;
System.out.println("wrong way");
}
}
catch (IOException ioe1){
}
}
long start = System.nanoTime();
byteWay = inWay.getBytes();
for (int i = 0; i < byteWay.length; i++) {
if ( ( byteWay[i] == 78 ) || ( byteWay[i] == 110) ) {
cntX += 1;
}
else if (( byteWay[i] == 83 ) || ( byteWay[i] == 115)){
cntX -= 1;
}
else if (( byteWay[i] == 69 ) || ( byteWay[i] == 101)){
cntY += 1;
}
else if (( byteWay[i] == 69 ) || ( byteWay[i] == 101)) {
cntY += 1;
}
else if (( byteWay[i] == 87 ) || ( byteWay[i] == 119)) {
cntY -= 1;
}
}
for (int i = 0; i < Math.abs(cntX); i++) {
if (cntX > 0) {
shortestWay.append("N");
}
else {
shortestWay.append("S");
}
}
for (int i = 0; i < Math.abs(cntY); i++) {
if (cntY > 0) {
shortestWay.append("E");
}
else {
shortestWay.append("W");
}
}
byteWays = String.valueOf(shortestWay).toCharArray();
Arrays.sort(byteWays);
shortestWay.setLength(0);
shortestWay.append(byteWays);
System.out.println("shortestWay is :" + shortestWay);
long end = System.nanoTime();
System.out.println("total cost time :" + (end - start) + "(ns)" + "/" + Float.valueOf(String.valueOf(end - start))/1000000 + "(ms)");
}
}