6、华为OD机试算法题——坐标移动

地址:坐标移动_牛客题霸_牛客网

示例代码:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = 0, y = 0;
        String str = sc.next();
        String string = str.toLowerCase();
        String[] split = string.split(";");
        for (String s : split) {
            // 判断当前s是否有效
            if (!s.matches("[wasd][1-9][0-9]?")) {
                continue;
            }
            // 方向
            String dir = s.substring(0, 1).toLowerCase();
            // 移动距离
            int dis = Integer.parseInt(s.replace(dir, ""));
            switch (dir) {
                case "w":
                    y += dis;
                    break;
                case "a":
                    x -= dis;
                    break;
                case "s":
                    y -= dis;
                    break;
                case "d":
                    x += dis;
                    break;
                default:
                    break;
            }
        }
        System.out.println(x + "," + y);
    }

 代码详解:

1. 首先将输入字符串切分开,获得单个的每一步操作字符串;

2. 遍历所有操作字符串s,使用正则表达式判断 s  是否有效;

3. 根据wasd判断操作方向;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值