牛客: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")
相关推荐
HMS Core16 小时前
消息推送策略:如何在营销与用户体验间找到最佳平衡点
华为·harmonyos·ux
Brianna Home17 小时前
【案例实战】鸿蒙分布式调度:跨设备协同实战
华为·wpf·harmonyos
Bert丶seven17 小时前
鸿蒙Harmony实战开发教学(No.4)-RichText组件基础到高阶介绍篇
华为·harmonyos·arkts·鸿蒙·鸿蒙系统·arkui·开发教程
安卓开发者1 天前
鸿蒙NEXT鼠标光标开发完全指南
华为·计算机外设·harmonyos
●VON1 天前
重生之我在大学自学鸿蒙开发第九天-《分布式流转》
学习·华为·云原生·harmonyos·鸿蒙
Bert丶seven1 天前
鸿蒙Harmony实战开发教学(No.7)-Image组件基础到进阶篇
华为·harmonyos·arkts·鸿蒙·鸿蒙系统·arkui·开发教学
Bert丶seven2 天前
鸿蒙Harmony实战开发教学(No.6)-Search组件基础到进阶篇
华为·harmonyos·arkts·鸿蒙·鸿蒙系统·arkui·开发教学
安卓开发者2 天前
鸿蒙NEXT传感器开发概述:开启智能感知新时代
华为·harmonyos
nju_spy2 天前
华为AI岗 -- 笔试(一)
人工智能·深度学习·机器学习·华为·笔试·dbscan·掩码多头自注意力