题解 | #坐标移动#
坐标移动
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]); } }