题解 | 坐标移动

坐标移动

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

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static char[] directions = {'A','S','W','D'};
    static Map<Character,int[]> map = new HashMap<>();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String[] strs = in.nextLine().split(";");
        int x = 0;
        int y = 0;
        map.put('A', new int[]{-1, 0});
        map.put('S', new int[]{0, -1});
        map.put('W', new int[]{0, 1});
        map.put('D', new int[]{1, 0});
        for(int i = 0; i < strs.length; i++){
            if(isValid(strs[i])){
                int number = Integer.parseInt(strs[i].substring(1));
                int[] move = map.get(strs[i].charAt(0));
                x += move[0] * number;
                y += move[1] * number;
            }
        }
        System.out.print(x + "," + y);
    }

    public static boolean isValid(String str){
        int n = str.length();
        if( n < 2 || n >3){
            return false;
        }
        boolean found = false;
        boolean digitfound =false;
        for(char direction : directions){
            if(str.charAt(0) == direction){
                found = true;
                break;
            }
        }
        try{
            if(Integer.parseInt(str.substring(1,str.length())) >= 1 || Integer.parseInt(str.substring(1,str.length())) <= 99){
                digitfound = true;
            }
        }catch (Exception e){
            return false;
        }

        return digitfound && found;
    }
}

全部评论

相关推荐

10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
牛牛不会牛泪:脉脉太多这种了,纯水军
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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