题解 | #坐标移动#

坐标移动

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

#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <vector>
using namespace std;

const string valid = "ADWS";

int main() {
    auto check = [](const string& str) -> int {
        if (str.empty()) {
            return -1;
        } else {
            if (valid.find(str[0]) == string::npos) {
                return -1;
            } else {
                int tmp = 0;
                for (int i = 1; i < str.size(); ++i) {
                    if (str[i] >= '0' && str[i] <= '9') {
                        tmp = tmp * 10 + (str[i] - '0');
                    } else {
                        return -1;
                    }
                }
                return tmp;
            }
        }
    };
  	// 利用std::istringstream做字符串分割处理
    string str;
    cin >> str;
    std::istringstream iss(str);
    string token;
    vector<int> pos{0,0};
    while(std::getline(iss, token, ';')) {
        int ck = check(token);
        // cout << " check = " << ck << endl;
        if (ck != -1) {
            switch (token[0]) {
            case 'A': pos[0] -= ck; break;
            case 'S': pos[1] -= ck; break;
            case 'W': pos[1] += ck; break;
            case 'D': pos[0] += ck; break;
            }
        }
        // cout << "cur = " << pos[0] << "," << pos[1] << endl;
    }
    cout << pos[0] << "," << pos[1] << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务