题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.Scanner;
import java.util.*;
// 先分割的字符串进行坐标转换,无效的也转
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String s = in.nextLine();
int[] out = move(s);
System.out.println(out[1] + "," + out[0]);
}
}
static ArrayList<String> base;
static {
base = new ArrayList<String>();
base.add("D");
base.add("S");
base.add("A");
base.add("W");
}
public static int[] move(String s) {
int[] start = new int[]{0,0};
String[] split = s.split(";");
int n = split.length;
for(int i = 0; i < n; i++) {
int[] dir = check(split[i]);
start[0] += dir[0];
start[1] += dir[1];
}
return start;
}
public static int[] check(String dirs) {
String dirl = null;
int len = -1;
int[] to = new int[]{0,0};
if(dirs.equals("")) return to;
for(int i = 0; i < dirs.length(); i++) {
if(i == 0) {
if(base.contains(dirs.charAt(i)+"")) {
dirset = true;
dirl = dirs.charAt(i)+"";
} else {
return to;
}
} else {
int off = 0;
int num = 0;
while(i+off < dirs.length() && Character.isDigit(dirs.charAt(i+off))) {
num = num *10 + (dirs.charAt(i+off) - '0');
off++;
}
if(i + off == dirs.length()) {
len = num;
break;
} else {
return to;
}
}
}
if(dirl.equals("D")) {
to[1] += len;
} else if (dirl.equals("W")) {
to[0] += len;
} else if (dirl.equals("A")) {
to[1] -= len;
} else {
to[0] -= len;
}
return to;
}
}
查看10道真题和解析