牛客: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")
相关推荐
m0_738185828 小时前
Flutter 鸿蒙化实战:flutter_app_badger 适配 OpenHarmony,应用角标
flutter·华为·harmonyos·鸿蒙
袁震9 小时前
HarmonyOS 7 深色模式与全局换肤实战:一套色板管到底
华为·harmonyos
resh_people10 小时前
开源鸿蒙平台 KMP/CMP 三方库「Okio」适配全流程
华为·开源·harmonyos
-madongyu-11 小时前
HCIE-GaussDB V2.0 笔试考点总览:模块权重、核心要点与高频数字速记
数据库·华为·gaussdb
轻口味11 小时前
HarmonyOS 7 新特性2:音频编创——轻音台里的降噪、环绕与格式转换
华为·音视频·harmonyos·鸿蒙·音频编创
极客范儿12 小时前
华为HCIP网络工程师认证—DHCP、NAT和 PPPOE
网络·华为
m0_7381858212 小时前
Flutter 鸿蒙化实战:flutter_blue_plus 适配 OpenHarmony,蓝牙扫描连接开箱即用
flutter·华为·harmonyos·鸿蒙
m0_7381858213 小时前
Flutter 鸿蒙化实战:flutter_background_service 适配 OpenHarmony,后台服务
flutter·华为·harmonyos·鸿蒙
less_1213813 小时前
HarmonyOS WPS Open SDK 快速入门:HAR 集成到 sendRequest 打开文档
华为·harmonyos·wps
resh_people15 小时前
开源鸿蒙平台 KMP/CMP 三方库「kotlinx-datetime」适配全流程
华为·开源·harmonyos