题目拿到第一步就是想到如何判断输入值是合法的,第一反应就是用正则表达式:

^[A|W|S|D]\d{1,2}$

所以代码如下:

package huawei;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String operation = in.next();
            List<String> fineOperations = new ArrayList<>();
            String[] operations = operation.split(";");
            for (String s : operations) {
                if (isFine(s)) {
                    fineOperations.add(s);
                }
            }
            Tuple<Integer, Integer> result = Tuple.of(0, 0);
            for (String fineOperation : fineOperations) {
                 move(fineOperation, result);
            }
        System.out.println(result);
        }
    }

    private static Tuple<Integer, Integer> move(String operation, Tuple<Integer, Integer> tuple) {
        String direction = operation.substring(0, 1);
        int step = Integer.parseInt(operation.substring(1));

        switch (direction) {
            case "A":
                tuple.l -= step;
                break;
            case "D":
                tuple.l += step;
                break;
            case "W":
                tuple.r += step;
                break;
            case "S":
                tuple.r -= step;
                break;
            default:
        }

        return tuple;
    }

    private static boolean isFine(String s) {
        Pattern pattern = Pattern.compile("^[A|D|S|W]\\d{1,2}$");
        Matcher matcher = pattern.matcher(s);
        return matcher.find();
    }

}


class Tuple<L, R> {
    L l;
    R r;

    private Tuple(L l, R r) {
        this.l = l;
        this.r = r;
    }

    public static <L, R> Tuple<L, R> of(L l, R r) {
        return new Tuple<>(l, r);
    }

    @Override
    public String toString() {
        return l + "," + r;
    }
}