牛客华为算法-HJ17 坐标移动

我爱海鲸 2025-04-21 12:43:15 暂无标签

简介华为OD

坐标移动_牛客题霸_牛客网

描述

我们定义一个无限大的二维网格上有一个小人,小人初始位置为 (0,0) 点,小人可以读取指令上下左右移动。

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

输出小人最终的坐标。

输入描述:

在一行上输入一个长度 1≦length(s)≦104 ,仅由可见字符构成的字符串 s ,代表输入的指令序列。

输出描述:

在一行上输出一个两个整数,代表小人最终位置的横纵坐标,使用逗号间隔。
解法一(java):
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.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        // System.out.println((int)'A'); 65
        // System.out.println((int)'D'); 68
        // System.out.println((int)'W'); 87
        // System.out.println((int)'S'); 83
        String value = in.nextLine();
        String[] strs = value.split(";");
        int x = 0;
        int y = 0;
        for (int i = 0 ; i < strs.length ; i++) {
            if (!isVaild(strs[i])) {
                continue;
            }
            String com = strs[i].substring(0,1);
            int v = Integer.valueOf(strs[i].substring(1));
            if ("A".equals(com)) {
                x = x - v;
            } else if ("D".equals(com)) {
                x = x + v;
            } else if ("W".equals(com)) {
                y = y + v;
            }  else if ("S".equals(com)) {
                y = y - v;
            }
        }
        System.out.println(x+","+y);
    }


    public static boolean isVaild(String str) {
        if (str == null || "".equals(str.trim())) {
            return false;
        }
        int ch = str.charAt(0);
        if (ch != 65 && ch != 68 && ch != 87 && ch != 83) {
            return false;
        }
        int n = 0;
        try {
            n = Integer.valueOf(str.substring(1));
        } catch(Exception e) {
            return false;
        }
        if (n > 99 || n < 1) {
            return false;
        }
        return true;
    }

}

思路:定义坐标点,解析指令,根据指令 移动坐标点即可。

你好:我的2025