题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
- 先使用
;
分割字符串 - 使用
正则
和stream
过滤不合规的坐标
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
/**
* class com.sloera.nowcoder
* user sloera
* date 2022/2/27
*/
public class Main {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
final String s = in.nextLine();
handle(s);
}
}
private static void handle(String s) {
AtomicInteger x = new AtomicInteger();
AtomicInteger y = new AtomicInteger();
final Pattern compile = Pattern.compile("^[ASDW]\\d{1,2}$");
Arrays.stream(s.split(";")).filter(l -> compile.matcher(l).find()).forEach(l -> {
final char c = l.charAt(0);
final int step = Integer.parseInt(l.substring(1));
switch (c) {
case 'A': x.addAndGet(-step); break;
case 'D': x.addAndGet(step); break;
case 'W': y.addAndGet(step); break;
case 'S': y.addAndGet(-step); break;
default:;
}
});
System.out.println(x + "," + y);
}
}