题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
观察一个正确的字符,例如str="A10"
- str中非数字的字符只有一个,且其为第一个字符,且其为方向,这里为A;
- str中不能只存在一个方向,故str大小大于1。
只处理符合上述标准的字符串即可。
#include<iostream>
#include<vector>
using namespace std;
auto getSubStr(string& s)
{
pair<int,int> position={0,0}; //要返回的位置
int begin=0, end=0, no_num=0, step;//begin:每一步的第一个字符;begin:每一步的最后一个字符;no_num每步里面非数字的个数;step步长
for(char a:s)
{
if(a!=';')
{
if(a<47||a>58)
no_num++;
}
else
{
if(no_num==1&&end-begin>1)//只有字符串中非数字的字符数为1,且非数字为方向时,且存在步长时 例如:A10
{
step=stoi(s.substr(begin+1,end-begin));
if(s[begin]=='A') position.first-=step;
else if(s[begin]=='D') position.first+=step;
else if(s[begin]=='S') position.second-=step;
else if(s[begin]=='W') position.second+=step;
}
begin=end+1;//转到下一步
no_num=0;
}
end++;
}
return position;
}
int main()
{
string s;
while(cin>>s)
{
auto step=getSubStr(s);
cout<<step.first<<","<<step.second<<endl;
}
return 0;
}
腾讯成长空间 1159人发布
查看9道真题和解析
