首页 > 试题广场 >

坐标移动

[编程题]坐标移动
  • 热度指数:606804 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}我们定义一个无限大的二维网格上有一个小人,小人初始位置为 (0,0) 点,小人可以读取指令上下左右移动。

\hspace{15pt}一个合法的指令由三至四个符号组成:
\hspace{23pt}\bullet\,第一个符号为 \texttt{ 中的一个,代表小人移动的方向;分别代表向左、向右、向上、向下移动;记某个时刻小人的坐标为 (x,y) ,向左移动一格即抵达 (x-1,y) 、向右移动一格即抵达 (x+1,y) 、向上移动一格即抵达 (x,y+1) 、向下移动一格即抵达 (x,y-1)
\hspace{23pt}\bullet\,最后一个符号为 \texttt{ ,代表指令的结束,该符号固定存在;
\hspace{23pt}\bullet\,中间为一个 \texttt{1-99} 的数字,代表小人移动的距离。
\hspace{15pt}如果你遇到了一个不合法的指令,则直接忽略;例如,指令 \texttt{ 是不合法的,因为 \texttt{100} 超出了 \texttt{1-99} 的范围;\texttt{ 也是不合法的,因为 \texttt{Y} 不是 \texttt{ 中的一个。

\hspace{15pt}输出小人最终的坐标。

输入描述:
\hspace{15pt}在一行上输入一个长度 1 \leqq {\rm length}(s) \leqq 10^4 ,仅由可见字符构成的字符串 s ,代表输入的指令序列。


输出描述:
\hspace{15pt}在一行上输出一个两个整数,代表小人最终位置的横纵坐标,使用逗号间隔。
示例1

输入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出

10,-10

说明

\hspace{15pt}对于这个样例,我们模拟小人的移动过程:
\hspace{23pt}\bullet\,第一个指令 \texttt{ 是合法的,向左移动 10 个单位,到达 (-10,0) 点;
\hspace{23pt}\bullet\,第二个指令 \texttt{ 是合法的,向下移动 20 个单位,到达 (-10,-20) 点;
\hspace{23pt}\bullet\,第三个指令 \texttt{ 是合法的,向上移动 10 个单位,到达 (-10,-10) 点;
\hspace{23pt}\bullet\,第四个指令 \texttt{ 是合法的,向右移动 30 个单位,到达 (20,-10) 点;
\hspace{23pt}\bullet\,第五个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第六个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第七个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第八个指令 \texttt{ 不合法,跳过;
\hspace{23pt}\bullet\,第九个指令 \texttt{ 是合法的,向左移动 10 个单位,到达 (10,-10) 点。
示例2

输入

ABC;AKL;DA1;

输出

0,0
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            while (in.hasNextLine()) {
                String s = in.nextLine();
                StringBuilder sb = new StringBuilder(s);
                int end = sb.lastIndexOf(";");
                int start = 0;
                int pos = sb.indexOf(";");
                String order = sb.substring(start, pos);
                int x = 0, y = 0;
                while (pos <= end) {
                    char[] orderArr = order.toCharArray();
                    if (orderArr.length > 1) {
                        char ch = orderArr[0];
                        if (ch == 'A' || ch == 'D' || ch == 'W' || ch == 'S') {
                            StringBuilder step = new StringBuilder();
                            boolean isValid = true;
                            for (int i = 1; i < orderArr.length; i++) {
                                if (orderArr[i] >= '0' && orderArr[i] <= '9') {
                                    step.append(orderArr[i]);
                                } else {
                                    isValid = false;
                                    break;
                                }
                            }
                            if (isValid) {
                                int stepNum = Integer.parseInt(step.toString());
                                switch (ch) {
                                    case 'A':
                                        x -= stepNum;
                                        break;
                                    case 'D':
                                        x += stepNum;
                                        break;
                                    case 'W':
                                        y += stepNum;
                                        break;
                                    case 'S':
                                        y -= stepNum;
                                        break;
                                }
                            }
                        } // if ch end

                    }// if length end
                    if (pos == end) break;
                    start = pos + 1;
                    pos = sb.indexOf(";", pos + 1);
                    order = sb.substring(start, pos);
                } // while end
                System.out.println(x + "," + y);
            }// input end
        }
    }
}
发表于 2025-03-28 11:04:56 回复(0)
mport java.awt.List;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int x = 0;
        int y = 0;
        String[] array = s.split(";");
        for(String str : array){
            if (!str.matches("[ADWS]\\d+")) { // 验证格式是否为 "字母+数字"
                continue; // 跳过无效格式
            }
            int number = Integer.parseInt(str.substring(1));
            switch (str.charAt(0)) {
                case 'A':
                    x -= number;
                    break;
                case 'D':
                    x += number;
                    break;
                case 'W':
                    y += number;
                    break;
                case 'S':
                    y -= number;
                    break;
            }
        }
        System.out.println(x + "," + y);
    }
}
发表于 2025-03-21 20:04:20 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        String[] arr = s.split(";");
        int x = 0;
        int y = 0;
        for(String a : arr)
        {
            if(a == null || a.trim().length() < 2 || a == "")
            {
                continue;
            }
            char cur = a.charAt(0);
            if(cur=='A'||cur=='D'||cur=='W'||cur=='S')
            {
                String ss = a.substring(1);
                boolean judge = true;
                //判断后面的步数指令有没有字母
                for(int i = 0;i < ss.length();i++)
                {
                    if(ss.charAt(i) > '9' || ss.charAt(i) < '0')
                    {
                        judge = false;
                        break;
                    }
                }
                if(judge == false)
                {
                    continue;
                }
                else
                {
                    int step = Integer.parseInt(ss);
                    if(step < 1 || step > 100)
                    {
                        continue;
                    }
                    if(cur == 'A')
                    {
                        x -= step;
                    }
                    else if(cur == 'D')
                    {
                        x += step;
                    }
                    else if(cur == 'W')
                    {
                        y += step;
                    }
                    else if(cur == 'S')
                    {
                        y -= step;
                    }
                }
            }
            else
            {
                continue;
            }
        }
        System.out.print(x + "," + y);
    }
}


发表于 2025-03-12 09:39:34 回复(0)
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.nextLine();
            String[] arr = str.split(";");
            int x = 0;
            int y = 0;
            for (String m : arr) {
                if (m.length() > 3 || m.length() < 2) {
                    continue;
                }
                try {
                    int num = Integer.parseInt(m.substring(1));
                    char c = m.charAt(0);
                    if (c == 'A') {
                        x -= num;
                    } else if (c == 'D') {
                        x += num;
                    } else if (c == 'S') {
                        y -= num;
                    } else if (c == 'W') {
                        y += num;
                    }
                } catch (Exception e) {
                }
            }
            System.out.println(x + "," + y);
        }
    }
发表于 2025-03-10 18:32:15 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int[][] indexNum = new int[1][2];//默认0 0
            String arr = in.nextLine();
            arr=arr.replaceAll(";;",";");
            String[] str=arr.split(";");
            for(String s:str){
                if(s.length()>3||s.length()<2) continue;
                if(!s.matches(".*[^ASDW]+")) continue;
                if((!s.matches("^[^ASDW]*[ASDW][^ASDW]*$"))) continue;
                if(s.charAt(0)=='A'){
                    indexNum[0][0]= indexNum[0][0]-Integer.valueOf(s.substring(1,s.length()));
                }else if(s.charAt(0)=='S'){
                    indexNum[0][1]= indexNum[0][1]-Integer.valueOf(s.substring(1,s.length()));
                }else if(s.charAt(0)=='D'){
                    indexNum[0][0]= indexNum[0][0]+Integer.valueOf(s.substring(1,s.length()));
                }else if(s.charAt(0)=='W'){
                    indexNum[0][1]= indexNum[0][1]+Integer.valueOf(s.substring(1,s.length()));
                }
            }
            System.out.println(indexNum[0][0]+","+indexNum[0][1]);
        }
    }
}

发表于 2025-02-24 15:22:23 回复(0)
    public static void printCoordinate(){
        Scanner in = new Scanner(System.in);
        System.out.println("enter coordinates: ");
        // A10;S20;W10;D30;X;A1A;B10A11;;A10;
        String input = in.nextLine();
        String[] strIn = input.split(";");
        System.out.println(Arrays.toString(strIn));
        int x = 0;
        int y = 0;
        for (String step : strIn){
            if (step.charAt(0) == 'W' || step.charAt(0) == 'S' || step.charAt(0) == 'A' || step.charAt(0) == 'D'){
                String stepStr = step.substring(1, 3);
                if (step.length() >= 3 || step.trim().isEmpty()) {
                    continue;
                } else{
                    try{
                        int stepNum = Integer.parseInt(stepStr);
                        if (0 < stepNum && stepNum < 100){
                            if (step.charAt(0) == 'W'){
                                y += stepNum;
                            }else if(step.charAt(0) == 'S'){
                                y -= stepNum;
                            }else if(step.charAt(0) == 'A'){
                                x -= stepNum;
                            }else if(step.charAt(0) == 'D'){
                                x += stepNum;
                            }
                        }
                    }catch(NumberFormatException e){
                        continue;
                    }
                }
            }
        }
        System.out.println(x + "," + y);
    }
有没有大佬可以指点一下为什么我这个处理不了只有一个;的情况啊
发表于 2025-02-19 18:40:44 回复(0)
不怎么会正则,就直接Integer.valueOf来捕获异常
import java.util.LinkedList;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String[] split = s.split(";");
        int x = 0;
        int y = 0;
        for (int i = 0; i < split.length; i++) {
            int move = islegal(split[i]);
            if (move != -1) { //指令合法
                char direction = split[i].charAt(0);
                if (direction == 'A') {
                    x -= move;
                } else if (direction == 'D') {
                    x += move;
                } else if (direction == 'W') {
                    y += move;
                } else if (direction == 'S') {
                    y -= move;
                }
            }
        }
        System.out.println(x + "," + y);
    }

    public static int islegal(String s) { //返回距离
        if (s.length() < 2)
            return -1;
        char direction = s.charAt(0);
        if (direction == 'A' || direction == 'W' || direction == 'D' ||
                direction == 'S') {
            String move = s.substring(1, s.length());
            if (move.isEmpty())
                return -1;
            int m = 0;
            try {
                m = Integer.valueOf(move);
            } catch (Exception e) { //不能将字符串转为数字
                return -1;
            }
            if (m >= 1 && m < 100)
                return m;
        }
        return -1;
    }

}


发表于 2025-02-11 19:25:42 回复(0)
String.split 分割 +  .substring 子串  +  .matches 正则
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int x = 0, y = 0;
        String s = in.next();
        String[] sp = s.split(";");

        for (int i = 0; i < sp.length; i++) {
            if (sp[i].length() < 2 || sp[i].length() > 3) // 初步筛选长度不合规的
                continue;
                
            String move = sp[i].substring(0, 1);
            if (move.matches("[ADWS]")) {
                s = sp[i].substring(1);
                if (s.matches("[0-9]{1,2}")) {  // 1-99
                    int d = Integer.parseInt(s);
                    if (move.equals("A")) {
                        x -= d;
                    } else if (move.equals("D")) {
                        x += d;
                    } else if (move.equals("W")) {
                        y += d;
                    } else if (move.equals("S")) {
                        y -= d;
                    }
                }
            }
        }

        System.out.print(x + "," + y);
    }
}




发表于 2025-01-26 22:29:18 回复(0)
这个应该不难,正则表达式我不太擅长,所以校验部分代码写的不太好
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    private static int X = 0;
    private static int Y = 0;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String input;

        do {
            input = scanner.nextLine();
            String[] strArrays = input.split(";");
            for (String temp : strArrays) {
                move(temp);
            }
            System.out.println(X + "," + Y);
        } while (scanner.hasNext() && !"0".equals(input));

    }

    public static void move(String input) {

        if (input.isEmpty() || input.length() > 3) {
            return;
        }

        String direction = input.substring(0, 1);
        String value = input.substring(1);

        try {
            int intValue = Integer.parseInt(value);
            if (intValue < 1 || intValue > 99) {
                return;
            }
        } catch (Exception e) {
            return;
        }

        if ("A".equals(direction)) {
            X -= Integer.parseInt(value);
        }

        if ("D".equals(direction)) {
            X += Integer.parseInt(value);
        }

        if ("W".equals(direction)) {
            Y += Integer.parseInt(value);
        }

        if ("S".equals(direction)) {
            Y -= Integer.parseInt(value);
        }
    }
}

发表于 2025-01-10 18:08:10 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();

        // 分割字符串得到命令数组
        String[] commands = str.split(";");
        int x = 0, y = 0;

        for(int i = 0; i < commands.length; i++) {
            if(isValid(commands[i])) {
                char dir = commands[i].charAt(0);
                int len = Integer.parseInt(commands[i].substring(1));
                if(dir == 'A') {
                    x -= len;
                }
                else if(dir == 'D') {
                    x += len;
                }
                else if(dir == 'W') {
                    y += len;
                }
                else if(dir == 'S') {
                    y -= len;
                }
            }
        }
        System.out.print(x + "," + y);
    }
    // 检查命令是否有效
    public static boolean isValid(String str) {
        if(str.equals(" ") || str.length() > 3 || str.length() < 2) {
            return false;
        }
        // 如果命令长度是3,检查要第三个字符  
        if(str.length() == 3 && !isDigit(str.charAt(2))) {
            return false;
        }
        if(isLetter(str.charAt(0)) && isDigit(str.charAt(1))) {
            return true;
        }
        return false;
    }
    // 检查命令的方向操作符是否有效
    public static boolean isLetter(char c) {
        if(c == 'A' || c == 'D' || c == 'W' || c == 'S') {
            return true;
        }
        return false;
    }
    // 检查字符是否是数字
    public static boolean isDigit(char c) {
        if(c >= '0' && c <= '9') {
            return true;
        }
        return false;
    }
}

发表于 2024-09-07 11:06:15 回复(0)
import java.util.*;
import java.util.regex.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 caset();
String s = in.nextLine();
if (s == null || s.isEmpty()) {
System.out.println("0,0");
return;
}

//分割命令
String[] subS = s.split(";");
if (subS == null || subS.length == 0) {
System.out.println("0,0");
return;
}

//命令的正则匹配
String pattern = "[ADWS]\\d{1,2}";

//起始坐标
int[] index = new int[] {0, 0};

for (int i = 0; i < subS.length; i++) {
if (Pattern.matches(pattern, subS[i])) {
//方向
String direction = subS[i].substring(0, 1);
//移动距离
String position = subS[i].substring(1, subS[i].length());
int x = Integer.parseInt(position);

if ("A".equalsIgnoreCase(direction)) {
index[0] -= x;
}
if ("D".equalsIgnoreCase(direction)) {
index[0] += x;
}
if ("W".equalsIgnoreCase(direction)) {
index[1] += x;
}
if ("S".equalsIgnoreCase(direction)) {
index[1] -= x;
}
}
}
System.out.println(index[0] + "," + index[1]);
}
}
}
发表于 2024-08-04 16:30:20 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
            String a = in.nextLine();
            //先按题干用;切分
            String[] b = a.split(";");
            int z=0;
            int y=0;
            //遍历
            for(int i=0;i<b.length;i++){
                String c = b[i];
                //判断开头是否为ASDW,再判断后续是否为纯数字,都满足则进行位置计算
                if(c.startsWith("A")&&c.substring(1).matches("\\d*")){
                    int num = Integer.parseInt(c.substring(1));
                    z=z-num;
                }else if(c.startsWith("S")&&c.substring(1).matches("\\d*")){
                    int num = Integer.parseInt(c.substring(1));
                    y=y-num;
                }else if(c.startsWith("D")&&c.substring(1).matches("\\d*")){
                    int num = Integer.parseInt(c.substring(1));
                    z=z+num;
                }else if(c.startsWith("W")&&c.substring(1).matches("\\d*")){
                    int num = Integer.parseInt(c.substring(1));
                    y=y+num;
                }
            }
            System.out.println(z +","+ y);
   
    }
}
发表于 2024-08-01 17:08:51 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static class Coordinate{
        int x;
        int y;
        public Coordinate(){
            this.x=0;
            this.y=0;
        }

        public void move(char direction,int dist){
            switch(direction){
                case 'W':
                    this.y+=dist;
                    break;
                case 'S':
                    this.y-=dist;
                    break;
                case 'A':
                    this.x-=dist;
                    break;
                case 'D':
                    this.x+=dist;
                    break;
                default:
                    return;
            }
        }

        public String GetCoordinate(){
            StringJoiner sj=new StringJoiner(",");

            return sj.add(this.x+"").add(this.y+"").toString();
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String s=sc.nextLine();

        System.out.println(GetResult(s));
    }

    //判断一个字符串是否为整数
    public static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static String GetResult(String s){
        String[] cds=s.split(";");

        Coordinate Cd=new Coordinate();

        for(int i=0;i<cds.length;i++){
            //去掉第一个字符,看剩下的是否为一个整数
            if(!isInteger(cds[i].substring(1))){
                i++;
                continue;
            }
            else{
                char direction=cds[i].charAt(0);
                int dist=Integer.parseInt(cds[i].substring(1));
                Cd.move(direction,dist);
            }
        }

        return Cd.GetCoordinate();
    }
}

发表于 2024-07-16 17:35:42 回复(0)
判断是否为空,判断开头是否为合法操作,判断结尾是否为数字,没有判断是否存在AS7这种情况
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('A', -1);
        map.put('D', 1);
        map.put('S', -1);
        map.put('W', 1);
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String source = in.next();
        String[] arr = source.split(";");
        int x = 0;
        int y = 0;
        for(int i = 0; i < arr.length; i ++) {
            // 判断坐标合法性
            String temp = arr[i].trim();
            if(temp.length() ==3||temp.length()==2) {//过滤空的
                char c = temp.charAt(0);
                if(temp.charAt(temp.length()-1)==' '||!(temp.charAt(temp.length()-1)<='9'&&temp.charAt(temp.length()-1)>='0'))
                {
                    continue;
                }
                if(map.containsKey(c)) {//操作符合ADWS
                    //读取后面两位的内容
                    //为啥不用判断是否是AKL,DA1这种的
                  
                   int num=0;
                    if(temp.length() ==3)
                    {
                        int s=Character.getNumericValue(temp.charAt(1));
                        int g=Character.getNumericValue(temp.charAt(2));
                        num=s*10+g;
                    }
                    else{
                         int s=Character.getNumericValue(temp.charAt(1));
                      
                        num=s;

                    }
                   
                    try {
                        int numValue = Integer.valueOf(num);//
                        if('A' == c || 'D' == c) {
                            x = x + map.get(c) * numValue;
                        }else {
                            y = y + map.get(c) * numValue;
                        }
                    } catch(Exception e) {
                        continue;
                    }
                }
            }
        }
        System.out.println(x+","+y);
    }
}

发表于 2024-07-05 23:34:46 回复(1)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('A', -1);
        map.put('D', 1);
        map.put('S', -1);
        map.put('W', 1);
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String source = in.next();
        String[] arr = source.split(";");
        int x = 0;
        int y = 0;
        for(int i = 0; i < arr.length; i ++) {
            // 判断坐标合法性
            String temp = arr[i];
            if(temp.length() > 0) {
                char c = temp.charAt(0);
                if(map.containsKey(c)) {
                    //读取后面两位的内容
                    String num = temp.substring(1, temp.length());
                    try {
                        int numValue = Integer.valueOf(num);
                        if('A' == c || 'D' == c) {
                            x = x + map.get(c) * numValue;
                        }else {
                            y = y + map.get(c) * numValue;
                        }
                    } catch(Exception e) {
                        continue;
                    }
                }
            }
        }
        System.out.println(x+","+y);
    }
}

发表于 2024-07-04 17:37:10 回复(1)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            test(str);
        }
    }

    public static void test(String str) {
        String[] strArr = str.split(";");
        int a = 0;
        int b = 0;
        for (String s : strArr) {
            if (s.isEmpty()) {
                continue;
            }
            String c = s.substring(0, 1);
            int length =  s.length();
            String value = s.substring(1, length);
            if (!isDigit11(value)) {
                continue;
            }
            int step = Integer.valueOf(value);
            switch (c) {
                case "A":
                    a -= step;
                    break;
                case "S":
                    b -= step;
                    break;
                case "W":
                    b += step;
                    break;
                case "D":
                    a += step;
                    break;
            }
        }
        System.out.println(a + "," + b);
    }

    public static boolean isDigit11(String value) {
        if (value.equals(" ") || value.isEmpty()) {
            return false;
        }
        for (int i = 0; i < value.length(); i++) {
            if (!Character.isDigit(value.charAt(i))) {
                return false;
            }
        }
        return true;
    }

}


发表于 2024-07-02 12:50:56 回复(0)
注意修改牛客编译器里自动输入的 while (in.hasNextInt())要改成hasNext,否则用例不过。
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String[] input = in.nextLine().toLowerCase().split(";");
            
            int x = 0;
            int y = 0;

            char letter;
            long num;
            for(String tmp:input) {
                if(tmp==null || tmp.length()<=0) {
                    continue;
                }
                letter = tmp.charAt(0);
                try {
                    num = Long.parseLong(tmp.substring(1));
                } catch (Exception e) {
                    continue;
                }

                switch(letter) {
                    case 'a':
                        x -= num;
                        break;
                    case 's':
                        y -= num;
                        break;
                    case 'w':
                        y += num;
                        break;
                    case 'd':
                        x += num;
                        break;
                    default:
                        continue;
                }
            }

            System.out.println(x+","+y);
        }
    }
}

发表于 2024-06-16 16:56:18 回复(0)
感觉有点搞笑,一开始想直接过滤,发现根本过不了编译。说是方法不存在。但过了会儿又可以编译。。反复无常(非最佳实现,纯吐槽)
List<String> list = Arrays.stream(arr)
    .filter(o -> o != null && o.matches("[AWDS]\\d{1,2}"))
    .collect(Collectors.toList());


发表于 2024-05-29 17:57:05 回复(0)
import java.util.Scanner; 
import java.io.*;

public class Main {

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String line;
        while ((line = br.readLine()) != null && !line.isEmpty()) {
            // 初始化横纵坐标 {x, y}
            int[] coord = {0, 0};
            // 初始化移动命令
            char command = 'N';
            int distance = -1;
            // 解析数据
            int offset = 0;
            for (int i = 0; i < line.length(); i++) {
                char c = line.charAt(i);
                // 结算!
                if (c == ';') {
                    if (distance != -1) {
                        clac(coord, command, distance);
                    }
                    offset = 0;
                    distance = -1;
                    continue;
                }
                if (offset == -1) {
                    continue;
                }
                // 第一个字符, 默认视为命令
                if (offset == 0) {
                    command = c;
                    offset++;
                    continue;
                }
                // 第二个字符, 如果符合范围, 默认视为个位数
                if (offset == 1 && (c >= '0' && c <= '9')) {
                    distance = c - '0';
                    offset++;
                    continue;
                }
                // 第三个字符, 如果符合范围, 可以百分百确定个位数和十位数的值
                if (offset == 2 && (c >= '0' && c <= '9')) {
                    distance = distance * 10 + (c - '0');
                    offset++;
                    continue;
                }
                // 本次指令解析出现了非法指令, 暂时屏蔽 offset, 直到下一次结算 ';' 时再重新恢复
                offset = -1;
                // 本次指令解析出现了非法指令, 重置 distance
                distance = -1;
            }
            System.out.println(coord[0] + "," + coord[1]);
        }
        
    }

    public static void clac(int[] coord, char command, int distance) {
        switch (command) {
            case 'A':
                coord[0] = coord[0] - distance;
                break;
            case 'D':
                coord[0] = coord[0] + distance;
                break;
            case 'W':
                coord[1] = coord[1] + distance;
                break;
            case 'S':
                coord[1] = coord[1] - distance;
        }
    }

}
总共提交结果:答案正确
运行时间:9ms
占用内存:9428KB
使用语言:Java
用例通过率:100.00%
发表于 2024-05-23 12:57:39 回复(0)