题解 | #坐标移动#

坐标移动

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

华为机试 - 试水2

解题思路

  • 这道题比较简单,主要花在对不满足算法要求的输入的过滤上
  • 对于字符串去除空格,可以使用trim()replaceAll(" ","")
  • 对于字符串是否为纯数字的判断,可以利用Character.isDigit(str.charAt(i))依次对字符串中每个字符进行判断;
  • 将结果以字符串的形式输出(别写错成python的输出形式)

参考代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;


public class Main{

   public boolean isNumeric(String str){
       for(int i = 0; i < str.length(); ++i){
           if(!Character.isDigit(str.charAt(i))){
               return false;
           }
       }
       return true;
   }

   public static void main(String[] args) throws IOException {

        Main cls = new Main();
        Scanner scan = new Scanner(System.in);

        String input1 = scan.nextLine();
        String tokens[] = input1.split(";");

        Map<Character,Integer> map = new HashMap<Character,Integer>();
        map.put('A',-1);
        map.put('D',1);
        map.put('S',-1);
        map.put('W',1);
        int point[] = new int[]{0,0};
        for(int i = 0; i < tokens.length; ++i){
            String temp = tokens[i].trim();  //去除空格
            if(temp.length() > 1){
                char c = temp.charAt(0);
                //获得偏移量
                String offset = temp.substring(1,temp.length());
                if(c == 'A' || c == 'D'){
                    if(cls.isNumeric(offset)){
                        int a = Integer.parseInt(offset);
                        point[0] += a * map.get(c); 
                    }
                }
                else if(c == 'S' || c == 'W'){
                    if(cls.isNumeric(offset)){
                        int a = Integer.parseInt(offset);
                        point[1] += a * map.get(c); 
                    }
                }
            }
        }
       System.out.println(point[0] + "," + point[1]);
    }
}
全部评论
看完你的代码,还有一点需要验证,偏移量offset要求是两位数字以内
1 回复 分享
发布于 2023-04-11 22:15 河南

相关推荐

点赞 评论 收藏
分享
评论
4
8
分享

创作者周榜

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