题解 | #坐标移动#不使用库函数,自己实现各个功能
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29?tpId=37&tqId=21240&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=3&judgeStatus=undefined&tags=&title=
#include <iostream> #include <string> #include <vector> using namespace std; string legal = "ADWS"; // 方向指令的合法字符 bool find_legal(char a) { for (int i = 0; i < 4; i++) { if (a == legal[i]) return true; } return false; } vector<string> first(string input) {//对输入的字符串进行切割 int input_size = input.size(); vector<string> result; int left = 0; for (int right = 0; right < input_size; right++) { if (input[right] == ';') { string now = input.substr(left, right - left); if (!now.empty()) { result.push_back(now); } left = right + 1; } } return result; } vector<string> is_legal(const vector<string>& first) {//判断字符串是否合法,传入first函数处理得到的字符串 vector<string> result; for (const string& command : first) { int nums_size = command.size(); if (nums_size >= 2 && nums_size <= 3) { if (find_legal(command[0])) { bool valid = true; for (int k = 1; k < nums_size; k++) { if (!(command[k] >= '0' && command[k] <= '9')) { valid = false; break; } } if (valid) { result.push_back(command); } } } } return result; } int main() { int x = 0, y = 0; string input; cin >> input; vector<string> legal_input = is_legal(first(input)); for (const string& command : legal_input) { int move_cost = command.substr(1).empty() ? 0 : stoi(command.substr(1)); if (command[0] == 'A') { x -= move_cost; } else if (command[0] == 'D') { x += move_cost; } else if (command[0] == 'W') { y += move_cost; } else if (command[0] == 'S') { y -= move_cost; } } cout << x << ',' << y << endl; }