牛客: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")
相关推荐
IsITGirl11 小时前
HarmonyOS 鸿蒙 WuKong 稳定性测试报错 Failed to connect to AAMS(已解决)
华为·harmonyos
万物智能信息科技13 小时前
鸿蒙RS232驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
驱动开发·华为·开源·harmonyos·鸿蒙
less_1213815 小时前
鸿蒙 WPS Open SDK 接入指南:凭据申请、HAR 集成与 registerApp 校验
华为·harmonyos·wps
hunterandroid2 天前
HarmonyOS 长列表滚动性能优化:预渲染、离屏缓存与 GPU 合成策略
华为·前端框架
熊猫钓鱼>_>2 天前
Kotlin Multiplatform for OpenHarmony 实战:kotlinx-serialization JSON 适配
开发语言·华为·kotlin·华为云·json·harmonyos·code
马剑威(威哥爱编程)2 天前
【共创稿事节】HarmonyOS 7 Agent 开发实战 11:并发多会话隔离
华为·harmonyos
马剑威(威哥爱编程)2 天前
【共创稿事节】HarmonyOS 7 Agent 开发实战 03:Tool Calling 让 AI 查实时订单与库存
华为·harmonyos
倔强的石头1062 天前
把 Typst 搬上开源鸿蒙 PC:一次“干净”的移植记录
华为·开源·harmonyos
hqzing3 天前
把 glibc 移植到鸿蒙 PC 上:它能用来做什么
华为·harmonyos
OH_TPC3 天前
HarmonyOS APP开发---“习惯猫“习惯打卡App,需要用到这个库
华为·harmonyos·鸿蒙