题解 | #坐标移动#

坐标移动

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);
  }
}
全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务