华为在线编程之坐标移动C++实现
题目描述
开发一个坐标计算工具, 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)
C++代码实现如下:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib> //atoi
#include <cstring> //strlen,strcpy,strtok
using namespace std;
vector<string> split(const string &str, const string &pattern){
char *strc = new char[strlen(str.c_str())+1];
strcpy(strc, str.c_str());
vector<string> resultVec;
char *tempStr = strtok(strc, pattern.c_str());
while(tempStr != NULL ) {
resultVec.push_back(string(tempStr));
tempStr = strtok(NULL, pattern.c_str());
}
delete []strc;
return resultVec;
}
bool isValidStr(const string& str){
if(str.size()==0)
return false;
int nLen=str.size();
if(str[0]!='A' && str[0]!='W' && str[0]!='D' && str[0]!='S')
return false;
for(int i=1; i<nLen; i++){
if(!(str[i]>='0' && str[i]<='9'))
return false;
}
return true;
}
int main(){
vector<string> splitVec;
int x,y;
string strLine,str;
int num;
while(cin>>strLine){
x=0,y=0;
vector<string> splitVec = split(strLine, ";");
for(int i=0; i<splitVec.size(); i++){
str=splitVec.at(i);
if(isValidStr(str)){
if(str[0]=='A'){
num=atoi(str.substr(1).c_str());//c style:int atoi(const char*)
x -= num;
}else if(str[0]=='W'){
num=atoi(str.substr(1).c_str());
y += num;
}else if(str[0] == 'D'){
num=atoi(str.substr(1).c_str());
x += num;
}else if(str[0] == 'S') {
num=atoi(str.substr(1).c_str());
y -= num;
}
}
}
cout << x << "," << y << endl;
}
return 0;
}
今天先分享一题,mark一下。