题解 | #坐标移动#

坐标移动

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

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

bool isValid(string const& str) {  // 判断分割的字符串是否合法
    if (str.size() <= 1) return false;
    if ( !isalpha(str[0]) ) return false;
    for (int i = 1; i < str.size(); i++) {
        if (!isdigit(str[i])  ) return false;
    }
    return true;
}
void move(string& str, int& x, int& y) {  //根据合法字符串对左边进行移动
    int num = stoi(str.substr(1));
    switch (str[0]) {
        case 'W':
            y = y + num;
            break;
        case 'A':
            x = x - num;
            break;
        case 'S':
            y = y - num;
            break;
        case 'D':
            x = x + num;
            break;
    }
}
/*
int main() {
    int x = 0, y = 0;
    string strs;
    getline(cin, strs, '\n');
    string str = "";
    for (auto s : strs) {
        if (s == ';') {
            if (isValid(str)) {
                move(str, x, y);
                // cout<<x<<","<<y<<endl;
                str = "";
            } else {
                str = "";
            }

        } else {
            str += s;
        }
    }
    cout << x << "," << y << endl;
    return 0 ;
}*/

int main() {
    int x = 0, y = 0;
    string strs;
    getline(cin, strs);  // 获取原始字符串
    vector<string> str_vec;
    string str;
    stringstream ss;
    ss<< strs;
    while(getline(ss, str, ';')){  //根据 ';'对原始命令进行分割
        if(isValid(str)){   //判断分割得到的命令是否有效
            str_vec.push_back(str);
        }
    }
    for(auto s : str_vec){  //根据有效命令 对坐标进行移动
        move(s, x, y);
    }
    cout << x << "," << y << endl;
    return 0 ;
}

// 64 位输出请用 printf("%lld")

全部评论

相关推荐

在debug的柠檬精很迷人:好消息:现在HR挑三拣四 15年后 HR跪着求要简历 坏消息:被挑的是这代人,到时候求人的也是这代人。真好。
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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