题解 | #坐标移动#
坐标移动
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")