【牛客网 - 华为机试】HJ17 坐标移动
题目描述
开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
输入:
合法坐标为A(或者D或者W或者S) + 数字(两位以内)
坐标之间以;分隔。
非法坐标点需要进行丢弃。如AA10; A1A; % ; YAD; 等。
下面是一个简单的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
处理过程:
起点(0,0)
-
A10 = (-10,0)
-
S20 = (-10,-20)
-
W10 = (-10,-10)
-
D30 = (20,-10)
-
x = 无效
-
A1A = 无效
-
B10A11 = 无效
-
一个空 不影响
-
A10 = (10,-10)
结果 (10, -10)
注意请处理多组输入输出
输入描述:
一行字符串
输出描述:
最终坐标,以逗号分隔
示例1
输入
A10;S20;W10;D30;X;A1A;B10A11;;A10;
输出
10,-10
解题思路
正则表达式 + HashMap
package 笔试汇总.华为;/**
* Copyright (C), 2019-2021
* author candy_chen
* date 2021/4/10 15:36
*
* @Classname HJ17
* Description: 坐标移动
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* 用正则表达式 + HashMap
*/
public class HJ17 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Character,Integer> map = new HashMap<>();
while (sc.hasNext()){
String s = sc.nextLine();
int x = 0,y = 0; //起始坐标
String[] sArray = s.split(";");
String res = "[ADWS]\\d{1}\\d?";
for (int i = 0; i < sArray.length; i++) {
if (sArray[i].matches(res)){
map.put(sArray[i].charAt(0),map.getOrDefault(sArray[i].charAt(0),0) + Integer.valueOf(sArray[i].substring(1)));
}
}
x = x - map.get('A') + map.get('D');
y = y - map.get('S') + map.get('W');
System.out.println(x + "," + y);
map.clear();
}
sc.close();
}
}
方法二:
package 笔试汇总.华为;/**
* Copyright (C), 2019-2021
* author candy_chen
* date 2021/4/10 15:36
*
* @Classname HJ17
* Description: 坐标移动
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 字符串
*/
public class HJ17_1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String[] strs = s.split(";");
int[] point = new int[2];
for (String str : strs) {
//长度超过3,跳过
if (str.length() > 3){
continue;
}
int length;
try {
length = Integer.parseInt(str.substring(1));
}catch (Exception e){
continue;
}
if (str.charAt(0) == 'A' || str.charAt(0) =='S' || str.charAt(0) == 'D' || str.charAt(0) == 'W'){
if(str.charAt(0)=='A'){
point[0] -= length;
}
if(str.charAt(0)=='S'){
point[1] -= length;
}
if(str.charAt(0)=='D'){
point[0] += length;
}
if(str.charAt(0)=='W'){
point[1] += length;
}
}else {
continue;
}
}
System.out.printf("%d,%d\n",point[0],point[1]);
}
}