题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
void Cal_Pos(const string& pos_str)
{
int n = pos_str.size()-1;
if(n <= 1)
return;
int dir_p,p1,p2;
p1 = 1;p2 = 0;
dir_p = p2;
bool nn_flag = 0;
while(p1 <= n)
{
//方向符号位置为分号,往后移动一位
while(pos_str[dir_p] == ';' )
{
++p1;
++p2;
++dir_p;
}
//第一个不是方向字符
if( !IsDirect_Char(pos_str[dir_p]) )
{
while(pos_str[p1] != ';')
p1++;
//开始下一个判断
p2 = p1 + 1;
p1 = p2 + 1;
dir_p = p2;
}
else//第一个是方向字符
{
while(pos_str[p1] != ';')
{
if( !IsNum_char(pos_str[p1]) )//发现不是数字,则设置标志
nn_flag = 1;
p1++;
}
//当前p1所指向为分号位置
if(!nn_flag)//全为数字
{
//提取方向字符与有效数字
char tmp_dir = pos_str[dir_p];
int Len = p1 - p2 - 1;
string tmp_str = pos_str.substr(p2+1,Len);
int tmp_data = stoi(tmp_str);
//计算对应坐标
Cal_Distance(tmp_dir,tmp_data);
}
//更新下一次
p2 = p1 + 1;
p1 = p2 + 1;
dir_p = p2;
nn_flag = 0;//清除本次的标志
}
}
}
void Cal_Distance(char c,int data)
{
switch (c)
{
case 'A':
x_sum -= data;
break;
case 'D':
x_sum += data;
break;
case 'W':
y_sum += data;
break;
case 'S':
y_sum -= data;
break;
}
}
bool IsNum_char(char c)const
{
if( ((c-'0') >= 0) && ((c-'0') <= 9) )
return true;
return false;
}
bool IsDirect_Char(char c)const
{
if(c == 'A' || c == 'D' || c == 'W' || c == 'S')
return true;
return false;
}
int GetX_sum()const
{
return x_sum;
}
int GetY_sum()const
{
return y_sum;
}
Solution(int x,int y)
:x_sum(0),y_sum(0)
{
}
private:
int x_sum;
int y_sum;
};
int main()
{
string pos_str;
getline(cin, pos_str);
Solution s(0,0);
// cout << s.IsNum_char('2') << endl;
s.Cal_Pos(pos_str);
cout << s.GetX_sum() << "," << s.GetY_sum() << endl;
return 0;
}
