HJ17华为机试题解 | #坐标移动#

坐标移动

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

#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

// 将输入字符串strInput按照seq分隔符进行分割
vector<string> Split(string strInput, string sep = ";")
{
    vector<string> resultVec;
    while (strInput.find(sep) != string::npos) {
        auto found = strInput.find(sep);
        if (found != string::npos) {
            resultVec.push_back(strInput.substr(0, found));
            strInput = strInput.substr(found+1);
        }
    }
    resultVec.push_back(strInput);

    return resultVec;
}

// 判断分割后的单个字符串是否是合法的坐标
// @param str:输入字符串
// @param dx: 横向坐标偏移值
// @param dy: 纵向坐标偏移值
// @return 是否为合法的坐标字符串
bool IsValidPos(const string &str, int &dx, int &dy)
{
    if (str.size() < 2 || str.size() > 3) {
        return false;
    }
    char direction = str[0];
    if (str.size() == 2) {
        if (!isdigit(str[1])) {
            return false;
        }
    }
    if (str.size() == 3) {
        if (!isdigit(str[1]) || !isdigit(str[2])) {
            return false;
        }
    }
    int steps = stoi(str.substr(1));
    if (direction == 'A') {
        dx = -steps;
        dy = 0;
    } else if (direction == 'D') {
        dx = steps;
        dy = 0;
    }  else if (direction == 'W') {
        dx = 0;
        dy = steps;
    }  else if (direction == 'S') {
        dx = 0;
        dy = -steps;
    } else {
        dx = 0;
        dy = 0;
        return false;
    }
    return true;
}

int main() {
    string strInput;
    while (getline(cin, strInput)) { // 注意 while 处理多个 case
        vector<string> resultVec = Split(strInput, ";");
        int x = 0;
        int y = 0;
        for (auto item : resultVec) {
            int dx = 0, dy = 0;
            bool bRet = IsValidPos(item, dx, dy);
            if (bRet) {
                x += dx;
                y += dy;
            }
        }
        std::cout << x << "," << y << std::endl;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务