题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int main()
{
int x = 0;
int y = 0;
string s;
getline(cin, s);
queue<char> totalque;
queue<char> temp;
for (char c : s)
{
totalque.push(c);
}
// all string stored in totalque;
while (!totalque.empty())
{
if (totalque.front() == ';')
{
// logic compute
if (temp.size() > 1 && temp.size() <= 3)
{
// d means commands for wasd
// dist menas the distance to move
bool valid = true;
char d;
string dist;
d = temp.front();
if (d != 'W' && d != 'A' && d != 'S' && d != 'D')
{
valid = false;
}
temp.pop();
while (!temp.empty())
{
if (temp.front() >= '0' && temp.front() <= '9')
{
dist += temp.front();
temp.pop();
}
else
{
valid = false;
break;
}
}
if (valid)
{
int move = stoi(dist);
if (d == 'W')
y += move;
if (d == 'A')
x -= move;
if (d == 'S')
y -= move;
if (d == 'D')
x += move;
}
}
totalque.pop();
while (!temp.empty())
{
temp.pop();
}
}
else
{
temp.push(totalque.front());
totalque.pop();
}
}
cout << x << ',' << y << endl;
}
// 64 位输出请用 printf("%lld")
写的比较臃肿。思路就是用队列来存每一个运算,用;来分割一个个运算式子,再单独判断式子是否符合要求。