题解 | #坐标移动#

坐标移动

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

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String line = sc.nextLine();
            String[] arr = line.split(";");
            int x = 0;
            int y = 0;
            for (String s : arr) {
                // 过滤非法字符结果
                int length = s.length();
                if (length < 2) {
                    continue;
                }
                String reduceRemove = s.replaceAll("[ADWS]", "");
                if (length - reduceRemove.length() > 1) {
                    continue;
                }
                String invalidStr = s.replaceAll("[ADWS0-9]", "");
                if (invalidStr.length() > 0) {
                    continue;
                }
                switch (s.charAt(0)) {
                    case 'A':
                        x -= Integer.parseInt(s.substring(1));
                        break;
                    case 'D':
                        x += Integer.parseInt(s.substring(1));
                        break;
                    case 'W':
                        y += Integer.parseInt(s.substring(1));
                        break;
                    case 'S':
                        y -= Integer.parseInt(s.substring(1));
                        break;
                }
            }
            System.out.println(x + "," + y);
        }
        sc.close();
    }

}

更简洁的写法:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String line = sc.nextLine();
            String[] arr = line.split(";");
            int x = 0;
            int y = 0;
            for (String s : arr) {
                // 过滤非法字符结果
                if (!s.matches("[ADWS][0-9]{1,5}")) {
                    continue;
                }
                int digit = Integer.parseInt(s.substring(1));
                switch (s.charAt(0)) {
                    case 'A':
                        x -= digit;
                        break;
                    case 'D':
                        x += digit;
                        break;
                    case 'W':
                        y += digit;
                        break;
                    case 'S':
                        y -= digit;
                        break;
                }
            }
            System.out.println(x + "," + y);
        }
        sc.close();
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
坦荡的牛油果拿到了s...:简历最好压缩在一页,期望职位和其他没必要单独一个板块,竞赛经历合并到教育经历里,而且最好获奖了才写。最重要的是实习经历,写得有点简单 一眼看不出来参与的项目具体是什么,具体需求、问题是怎么挖掘、分析、解决的。但是才大一就这么卷了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务