题解 | #坐标移动#

坐标移动

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static List<Character> firstLetter = Arrays.asList('A','D','W','S');

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String next = null;
        while (in.hasNextLine()) { // 注意 while 处理多个 case
        next = in.nextLine();
        }

        int x = 0, y = 0;

        String[] arr = next.split(";");
        for(String str : arr) {
            boolean flag = validate(str);
            // System.out.print(flag);
            if(!flag) {
                continue;
            }

            char c = str.charAt(0);
            String s = str.substring(1);
            Integer i = Integer.valueOf(s);

            // System.out.print(c);
            // System.out.print(s);
            // System.out.print(i);
            // System.out.println();

            if (c == 'A') {
                x -= i;
            } else if (c == 'D') {
                x += i;
            } else if (c == 'W') {
                y += i;
            } else if (c == 'S') {
                y -= i;
            }
    
        }
        System.out.print(x + "," + y);
    }

    private static boolean validate(String str) {
        // System.out.println(str);
        if (str == null || str.length() <= 1) {
            // System.out.println("1false");
            return false;
        }
        
        int n = str.length();
        char[] arr = str.toCharArray();
        for(int i = 0; i < n; i++) {
            char c = arr[i];
            if (i == 0) {
                if (!firstLetter.contains(c)) {
                    // System.out.println("2false");
                    return false;
                }
                continue;
            }
            if (i == 1 && c == '0') {
                // System.out.println("3false");
                return false;
            }
            int k = c - '0';

            if (k < 0 || k > 9) {
                // System.out.println("4false");
                return false;
            }
        }

        return true;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
豆泥🍀:同26届,加油,我也还没找到查看图片
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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