题解 | 坐标移动

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

#include <iostream>
#include <string>
#include <cctype> // 用于 isdigit 函数
using namespace std;

// 判断一个字符串是否是合法的指令
bool isValidCommand(const string& cmd) {
    // 指令长度必须是 3 或 4
    if (cmd.length() < 3 || cmd.length() > 4) return false;

    // 第一个字符必须是 A/D/W/S
    char dir = cmd[0];
    if (dir != 'A' && dir != 'D' && dir != 'W' && dir != 'S') return false;

    // 最后一个字符必须是 ;
    if (cmd.back() != ';') return false;

    // 中间部分必须是数字,isdigit函数对cmd【i】进行判定,为数字字符返回true,反之为false
    for (size_t i = 1; i < cmd.length() - 1; ++i) {
        if (!isdigit(cmd[i])) return false;
    }

    // 提取数字部分,stoi是将字符串转换为数字的函数,substr(pos,L)是将从第pos个字符的位置开始,截取共计L长度的字符,将其从字符串中提取出来
    int distance = stoi(cmd.substr(1, cmd.length() - 2));
    if (distance < 1 || distance > 99) return false;

    return true;
}

// 解析指令并移动小人
void moveCharacter(const string& cmd, int& x, int& y) {
    if (!isValidCommand(cmd)) return;

    char dir = cmd[0];
    int distance = stoi(cmd.substr(1, cmd.length() - 2));

    switch (dir) {
        case 'A': x -= distance; break; // 向左
        case 'D': x += distance; break; // 向右
        case 'W': y += distance; break; // 向上
        case 'S': y -= distance; break; // 向下
    }
}

int main() {
    string s;
    getline(cin, s); // 读取输入

    int x = 0, y = 0; // 初始位置
    size_t pos = 0;

    // 遍历字符串,解析指令
    while (pos < s.length()) {
        size_t nextPos = s.find(';', pos); // 找到下一个分号
        if (nextPos == string::npos) break; // 如果没有分号,结束

        string cmd = s.substr(pos, nextPos - pos + 1); // 提取指令
        moveCharacter(cmd, x, y); // 移动小人

        pos = nextPos + 1; // 更新起始位置
    }

    // 输出最终坐标
    cout << x << "," << y << endl;

    return 0;
}

全部评论

相关推荐

站队站对牛:还是浙江学校欢迎
投递海康威视等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务