题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

import java.util.Scanner;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        int x = 0, y = 0;


        String[] strings = line.split(";");
        for (int i = 0; i < strings.length; i++) {
            String cmd = strings[i];
            Pattern pattern = Pattern.compile("^([A|D|W|S])([0-9]{1,2})$");
            Matcher matcher = pattern.matcher(cmd);
            if (matcher.find()) {

                String cmdChar = matcher.group(1);
                int step = Integer.parseInt(matcher.group(2));

                //        A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动
                if (cmdChar.equals("A")) {
                    x += step * (-1);

                } else if (cmdChar.equals("D")) {
                    x += step;

                } else if (cmdChar.equals("W")) {
                    y += step;

                } else if (cmdChar.equals("S")) {
                    y += step * (-1);
                }
//                System.out.println(x+","+y);

            } else {
//                System.out.println("错误指令" + cmd);
            }


        }

        System.out.println(x + "," + y);
    }


}

全部评论
正则提取指令和步骤
点赞 回复 分享
发布于 2023-02-02 16:02 上海

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务