牛客: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")
相关推荐
二二孚日1 小时前
自用华为ICT云赛道AI第三章知识点-昇腾芯片硬件架构,昇腾芯片软件架构
人工智能·华为
财经三剑客6 小时前
鸿蒙智行6月交付新车52747辆 单日交付量3651辆
华为·harmonyos
睿麒6 小时前
鸿蒙app 开发中的 map 映射方式和用法
华为·harmonyos
爱笑的眼睛1119 小时前
08-自然壁纸实战教程-视频列表-云
华为·harmonyos
二二孚日1 天前
自用华为ICT云赛道AI第三章知识点-MindSpore特性、MindSpore开发组件
人工智能·华为
生如夏花℡1 天前
HarmonyOS学习记录4
学习·华为·harmonyos
九章云极AladdinEdu1 天前
华为昇腾NPU与NVIDIA CUDA生态兼容层开发实录:手写算子自动转换工具链(AST级代码迁移方案)
人工智能·深度学习·opencv·机器学习·华为·数据挖掘·gpu算力
枫叶丹41 天前
【HarmonyOS Next之旅】DevEco Studio使用指南(四十二) -> 动态修改编译配置
华为·harmonyos·deveco studio·harmonyos next
众乐 认证1 天前
HUAWEI HiCar6.0的新变化
华为·hicar