牛客: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")
相关推荐
2501_919749031 小时前
华为鸿蒙免费排班APP—小羊排班
华为·harmonyos·鸿蒙
超爱西西鸭3 小时前
思维导图编辑体验:触摸交互与节点操作(ArkTS)
学习·华为·harmonyos
世人万千丶4 小时前
HarmonyOS 股票 K 线图完整源码与金融图表模板
学习·华为·金融·harmonyos·鸿蒙
YM52e6 小时前
ArkTS 2048 手感调优:棋盘渲染与滑动交互
华为·harmonyos
晴天166 小时前
HarmonyOS 和 React 对比-Day22
前端·华为·harmonyos
砚凝霜6 小时前
软考网络工程师|案例分析:华为全套综合实验核心知识点 & 考点总结
网络·华为
lilian2338 小时前
Harmony os 技术实战|拼豆制图20:用 finally 关闭 ImageSource、PixelMap 与文件句柄
华为·harmonyos
独守一片天20 小时前
HarmonyOS 鸿蒙碰一碰与跨端协同体验怎么设计?
华为·harmonyos
m0_749690231 天前
【寻迹校园 HarmonyOS NEXT 实战 03】NavPathStack 路由实战:18 个页面如何集中管理
华为·移动开发·harmonyos·arkui·navigation·navpathstack
m0_749690231 天前
【寻迹校园 HarmonyOS NEXT 实战 02】多模块工程拆解:entry、HAR 与 HSP 如何分工
华为·harmonyos·arkts·软件架构·har·hsp