题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
这道题的难点感觉就是怎么处理字符串。本题使用正则表达式是比较方便的,但是需要注意以下这种情况:
A;
当使用正则"\\d*"对其后面的数字进行匹配时,要判断'A'之后的字符串是否为空,如果是空的,则不必往下进行。如果使用正则"\\d+"对其后面的数字进行匹配时,则不用对'A'之后的字符串是否为空进行判断。
虽然样例没有出现这种情况,但是还是要考虑一下。
#include <bits/stdc++.h>
#include <regex>
using namespace std;
using LL = long long;
int main() {
string s, t;
while (getline(cin, s)) {
stringstream ss(s);
LL x = 0, y = 0;
while (getline(ss, t, ';')) {
if (t.empty()) continue;
string move_num = t.substr(1);
/*
方式1:
regex r("\\d+"); // +:至少匹配一次
if (regex_match(move_num, r))
方式2:
regex r("\\d*"); // *:匹配任意次
if ( move_num != "" && regex_match(move_num, r))
*/
regex r("\\d+");
if (regex_match(move_num, r) ) {
if (t[0] == 'W') {
y += stoi(move_num);
} else if (t[0] == 'A') {
x -= stoi(move_num);
} else if (t[0] == 'S') {
y -= stoi(move_num);
} else if (t[0] == 'D') {
x += stoi(move_num);
}
}
}
printf("%lld,%lld\n", x, y);
}
return 0;
}
#c++##华为##华为笔试#