牛客: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")
相关推荐
企业软文推广4 分钟前
奥迪A5L×华为:品牌营销视角下的燃油车智能突围战!
python·华为
爱笑的眼睛115 分钟前
HarmonyOS声明式UI开发:深入探索ArkUI与Stage模型
华为·harmonyos
爱笑的眼睛118 分钟前
HarmonyOS应用开发:深入理解声明式UI与弹窗交互的最佳实践
华为·harmonyos
Cobboo8 分钟前
HarmonyOS 5.1.1版本图片上传功能
华为·harmonyos
爱笑的眼睛1110 小时前
HarmonyOS 应用开发新范式:深入探索 Stage 模型与 ArkUI 声明式开发
华为·harmonyos
光锥智能14 小时前
小平板元年,华为MatePad Mini创出一片蓝海
华为·电脑
萌虎不虎17 小时前
【鸿蒙(openHarmony)自定义音频播放器的开发使用说明】
华为·音视频·harmonyos
李洋-蛟龙腾飞公司17 小时前
HarmonyOSAI编程万能卡片生成(一)
华为·ai编程·harmonyos
森之鸟20 小时前
开发中使用——鸿蒙播放本地mp3文件
华为·harmonyos
不是三毛没有半20 小时前
华为USG6000v2 NAT模式下IPSEC IKE V1 实验
网络·网络安全·华为