牛客:HJ17 坐标移动[华为机考][字符串]

学习要点

  1. string.find()
  2. string.substr()

题目链接

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

题目描述

解法:字符串操作

cpp 复制代码
// #include <iostream>
#include <bits/stdc++.h>
#include <map>
#include <string>
#include <unordered_map>
#include <utility>
using namespace std;

int main() {
    string big_str;
    getline(cin, big_str);
    multimap<char,int>pos_map;
    // 开始检查
    // 先将头直接的';'排除
    int pos = 0;
    while (big_str[pos] == ';') {
        pos++;
    }
    if ( pos >= big_str.size()) {
        cout << '0' << ',' << '0' << endl;
    } else {
        while (pos < big_str.size()) {
            // 先拿到单个元素
            int prev_pos = pos;
            pos = big_str.find(';', pos);
            string tmp = big_str.substr(prev_pos, pos - prev_pos);
            while (big_str[pos] == ';') {
                pos++;
                if (pos == big_str.size())   break; // 防止溢出
            }
            // 尺寸必须小于4
            if (tmp.size() >= 4)
                continue;
            // 第一个必须是WASD
            if (tmp[0] != 'A' && tmp[0] != 'W' && tmp[0] != 'S' && tmp[0] != 'D')
                continue;
            // 第二个必须是数字
            if (tmp[1] < '0' || tmp[1] > '9')
                continue;
            // 如果有第三个必须是数字
            if (tmp.size() == 3) {
                if (tmp[2] < '0' || tmp[2] > '9')
                    continue;
            }
            // 结果正确放入容器
            // pos_map[tmp[0]] = stoi(tmp.substr(1));
            pos_map.insert(make_pair(tmp[0],stoi(tmp.substr(1))));
        }
        // 开始计算
        int x = 0;
        int y = 0;
        for (auto& i : pos_map) {
            switch (i.first) {
                case 'A':
                    x = x - i.second;
                    break;
                case 'D':
                    x = x + i.second;
                    break;
                case 'W':
                    y = y + i.second;
                    break;
                case 'S':
                    y = y - i.second;
                    break;
                default:
                    break;
            }
        }
        cout << x << ',' << y << endl;
    }
}
// 64 位输出请用 printf("%lld")
相关推荐
子榆.9 分钟前
【2025 最新实践】Flutter 与 OpenHarmony 的“共生模式”:如何构建跨生态应用?(含完整项目架构图 + 源码)
flutter·华为·智能手机·electron
工程师华哥33 分钟前
华为数通HCIE实验新增排障的具体解读,故障怎么加?什么时候加?考生怎么应对?
华为·网络工程师·华为认证·故障排除·网络运维·hcie数通·2026hcie实验
赵得C38 分钟前
华为HCIA/微认证学习资料
华为·hcia·微认证
Neolnfra42 分钟前
华为无线网络AC+AP完整配置指南
网络协议·华为·wireshark·信息与通信
萌虎不虎10 小时前
【在鸿蒙系统中实现拍照预览功能】
华为·harmonyos
萌虎不虎12 小时前
【鸿蒙实现显示屏测试实现方法】
华为·harmonyos
不爱吃糖的程序媛16 小时前
Flutter 开发的鸿蒙AtomGit OAuth 授权应用
华为·harmonyos
不爱吃糖的程序媛1 天前
鸿蒙PC命令行开发 macOS 上解决 pkg-config 命令未安装的问题
macos·华为·harmonyos
yumgpkpm1 天前
Cloudera CDP7、CDH5、CDH6 在华为鲲鹏 ARM 麒麟KylinOS做到无缝切换平缓迁移过程
大数据·arm开发·华为·flink·spark·kafka·cloudera
狮子也疯狂1 天前
【生态互联】| 鸿蒙三方库的选择与适配策略
华为·harmonyos