牛客: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")
相关推荐
特立独行的猫a11 小时前
仓颉编程语言的并发编程:线程模型与使用实践
华为·线程·仓颉·仓颉语言
2501_9197490314 小时前
配置flutter鸿蒙的环境和创建并运行第一个flutter鸿蒙项目【精心制作】
flutter·华为·harmonyos
Fanmeang16 小时前
华为交换机VLAN技术详解:从基础到高级应用
运维·网络·华为·vlan·交换机·mux vlan
Fanmeang16 小时前
华为路由器核心技术详解:数据包的智能导航系统
运维·网络·华为·路由器·路由表·路由协议
赵得C20 小时前
智能体的范式革命:华为全栈技术链驱动下一代AI Agent
人工智能·华为·ai·ai编程
Fanmeang1 天前
华为防火墙基础功能详解:构建网络安全的基石
运维·网络·安全·华为·防火墙·策略·安全域
爱笑的眼睛111 天前
深入解析ArkTS类型系统:构建安全高效的HarmonyOS应用
华为·harmonyos
猫林老师1 天前
Flutter for HarmonyOS开发指南(四):国际化与本地化深度实践
flutter·华为·harmonyos
猫林老师1 天前
Flutter for HarmonyOS 开发指南(一):环境搭建与项目创建
flutter·华为·harmonyos
爱笑的眼睛111 天前
HarmonyOS通知消息分类管理的深度实践与架构解析
华为·harmonyos