题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
输入:
合法坐标为A(或者D或者W或者S) + 数字(两位以内)
坐标之间以;分隔。
非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。
下面是一个简单的例子 如:A10;S20;W10;D30;X;A1A;B10A11;;A10;
处理过程:起点(0,0)
+ A10 = (-10,0)
+ S20 = (-10,-20)
+ W10 = (-10,-10)
+ D30 = (20,-10)
+ x = 无效
+ A1A = 无效
+ B10A11 = 无效
+ 一个空 不影响
+ A10 = (10,-10)
结果 (10, -10)*/
int fun(string str)
{
//合法坐标 +数字 最多三位数
if (str.length()>3)
{
return -1;
}
//char c[2] = { 0 };
//不用看第一位 只需要确定后面的数字 没有字符
for (int i = 1; i < str.length(); i++)
{
//不在0-9范围内就是假的 返回false
if (!(*(str.substr(i, i + 1).data())>='0' && (*(str.substr(i, i + 1).data()) <= '9')))
{
return -1;
}
}
return stoi(str.substr(1));
}
int main()
{
string str;
string strdata;//表示;分割的字符串
getline(cin,str);
//初始坐标
int x = 0;
int y = 0;
//用一个容器来进行贮存
vector<string> vec;
int len = 0;
//找分割号; 来进行判断
while (str.find(';') !=-1)
{
strdata = str.substr(0, str.find(';'));
vec.push_back(strdata);
str = str.substr(str.find(';')+1);
}
//auto iter :vec
for (auto iter = vec.begin(); iter != vec.end();iter++)
{
//元素第一个为A,并且删除这个A后后续不能出现其他字符
if (((*iter).find('A') == 0))
{
if (fun(*iter) != -1)
{
x -= fun(*iter);
}
continue;
}
if (((*iter).find('D') == 0))
{
if (fun(*iter) != -1)
{
x += fun(*iter);
}
continue;
}
if (((*iter).find('S') == 0))
{
if (fun(*iter) != -1)
{
y -= fun(*iter);
}
continue;
}
if (((*iter).find('W') == 0))
{
if (fun(*iter) != -1)
{
y += fun(*iter);
}
continue;
}
}
cout <<x<<","<<y<< endl;
system("pause");
return 0;
}
查看6道真题和解析
