首页 > 试题广场 >

坐标移动

[编程题]坐标移动
  • 热度指数:556700 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

开发一个坐标计算工具, 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)

数据范围:每组输入的字符串长度满足 ,坐标保证满足 ,且数字部分仅含正数

输入描述:

一行字符串



输出描述:

最终坐标,以逗号分隔

示例1

输入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出

10,-10
示例2

输入

ABC;AKL;DA1;

输出

0,0
#include <iostream>
using namespace std;

bool law(string op) {
    if(op[0] != 'A' && op[0] != 'S' && op[0] != 'W' && op[0] != 'D') return false;
    op = op.substr(1);
    for(int i = 0; i < op.size(); i++) {
        if(op[i] >= '0' && op[i] <= '9') continue;
        return false;
    }
    return true;
}

int move(string op) {
    int num = 0, ind = 1;
    while(op[ind]) {
        num = num * 10 + op[ind] - '0';
        ind++;
    }
    return num;
}

int main() {
    string str;
    while(cin >> str) {
        int x = 0, y = 0, flag = 1;
        while(flag) {
            int ind = str.find(';');
            if(ind == str.size() - 1) flag = 0;
            string op = str.substr(0, ind);
            str = str.substr(ind + 1);
            if(!law(op)) continue;
            int m = move(op);
            switch(op[0]) {
                case 'A':
                    x -= m;
                    break;
                case 'W':
                    y += m;
                    break;
                case 'S':
                    y -= m;
                    break;
                case 'D':
                    x += m;
                    break;
            }
        }
        cout << x << "," << y << endl;
    }
    return 0;
}


发表于 2018-10-05 16:39:29 回复(0)
更多回答
string pattern= "(.)?([ADWS])([0-9]{1,2});";
    string str="";
    while(cin >> str)
    {
        int x = 0, y = 0;
        regex r(pattern);
        for(sregex_iterator it(str.begin(), str.end(), r), end_it; it != end_it; ++it)
        {
            if(!it->str(1).empty() && it->str(1) != ";")continue;
            else
            {
                switch(it->str(2)[0])
                {
                    case 'A':
                        x -= stoi(it->str(3));
                        break;
                    case 'D':
                        x += stoi(it->str(3));
                        break;
                    case 'W':
                        y += stoi(it->str(3));
                        break;
                    case 'S':
                        y -= stoi(it->str(3));
                        break;
                    default:
                        break;
                }
            }
        }
        cout << x <<"," <<y <<endl;
    }

正则表达式用的不熟,有没有表达式可以直接选出合格的序列
发表于 2022-07-10 17:05:38 回复(0)
#include<iostream>
#include<string>
using namespace std;

int main() {
    string str;
    int x = 0, y = 0;
    int num = 0;
    while (getline(cin, str, ';')) {
        for (int i = 1; i < str.length(); i++) {
            if (isdigit(str[i])) {
                num = num * 10 + (str[i] - '0');
            }
            else {
                num = 0;
                break;
            }
        }
        if (str[0] == 'W') {
            y += num;
            num = 0;
        }
        else if (str[0] == 'A') {
            x -= num;
            num = 0;
        }
        else if (str[0] == 'S') {
            y -= num;
            num = 0;
        }
        else if (str[0] == 'D') {
            x += num;
            num = 0;
        }
        else {
            num = 0;
            continue;
        }
    }
    cout << x << ',' << y;
}

发表于 2022-07-05 13:54:57 回复(0)
const arr = readline().split(";")
let reg = /^[ASWD]\d{1,2}$/
let newArr = arr.filter(item=> reg.test(item))
let res = [0,0]
newArr.forEach(item=>{
    let moveP = item.slice(0,1)
    switch(moveP){
        case 'A':
            res[0] = res[0]-item.slice(1)*1
            break;
        case 'D':
            res[0] = res[0]+item.slice(1)*1
             break;
        case 'W':
            res[1] = res[1]+item.slice(1)*1
             break;
        case 'S':
            res[1] = res[1]-item.slice(1)*1
             break;
    }
})
console.log(res.join(','))

发表于 2022-07-04 10:40:33 回复(0)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>

int ifstr(char* s)
{
    char cc = 'a';
    int countnum = strlen(s);
    if (countnum >3)
        return 0;
    if (s[0] == 'W' || s[0] == 'A' || s[0] == 'S' || s[0] == 'D')
    {
        int num = atoi(&s[1]);
        if (countnum == 3 && num > 9 && num <=99)
        {
            return num;
        }
        if (countnum == 2 && num > 0 && num <= 9)
        {
            return num;
        }
    }
    return 0;
}

int main()
{
    char c[5]={0};
    char cha;
    int count=0,x=0,y=0;
    while((cha=getchar())!='\n')
    {
        if(cha!=';')
        {
            c[count]=cha;
            count++;
        }
        else
        {
            c[count]='\0';
            count=0;
            int num =ifstr(c);
            if(num)
            {
                switch(c[0])
                {
                    case 'A': x=x-num;break;
                    case 'D': x=x+num;break;
                    case 'W': y=y+num;break;
                    case 'S': y=y-num;break;
                }
            }
        }
    }
    printf("%d,%d",x,y);
}      

发表于 2022-06-07 19:33:28 回复(0)
import re

def jug (text):
    global ll
    if text == '':
        return 0
    if text[-1].isdigit() and 1 < len(text) <= 3:
        pattern = re.compile(r'[asdwASDW]\d{1,2}')
        is_match = re.match(pattern, text)
        if is_match:
            ll.append(text.upper())

texts = input().split(';')
ll = []
x, y = 0, 0

for i in texts:
    jug(i)
for _ in ll:
    tmp = _[0]
    if tmp == 'A':
        x -= int(_[1:])
    elif tmp == 'D':
        x += int(_[1:])
    elif tmp == 'S':
        y -= int(_[1:])
    else:
        y += int(_[1:])
print(f'{x},{y}')


发表于 2022-06-04 16:47:41 回复(1)
#include<iostream>
#include<string>
#include<vector>

using namespace std;
bool check(string& s){            //检测子串是不是合法的
    if(s.size()>3 || s.size() < 2)   return false;
    bool flag1=false,flag2=false;
    if(s[0] == 'A' || s[0] == 'W' || s[0] == 'S' || s[0] == 'D'){
        flag1=true;
    }                            //是一位数字还是两位数字
    if((s.size() == 2 && s[1] >= '0' && s[1] <= '9') || (s.size() == 3 && s[1] >= '0' && s[1] <= '9'
                                                        && s[2] >= '0' && s[2] <= '9')){
        flag2=true;
    }
    return flag1 && flag2;
}
pair<int,int>addNum(string& s){    //获取子串中的坐标
    int n=s.size();
    char c=s[0];
    int num=stoi(s.substr(1));    //截取子串1号位到结尾的数字大小
    pair<int,int>ans={0,0};
    switch (c)
    {
        case 'A':ans.first=-num;break;
        case 'D':ans.first=num;break;
        case 'W':ans.second=num;break;
        case 'S':ans.second=-num;break;
    }
    return ans;
}

void Solution(string &str,int& x,int& y){
    int n=str.size();
    int l=0,r=0;
    while(r<n){
        while(str[r] != ';'){        
            r++;
        }
        string s=str.substr(l,r-l);    //双指针截除去';'的子串
        if(check(s)){
            x+=addNum(s).first;
            y+=addNum(s).second;
        }
        l=r+1;                        //跳过';',取下一位位置;
        r=l;
    }
}

int main(){
    string str;
    cin>>str;
    int x=0,y=0;
    Solution(str, x, y);
    cout<<x<<','<<y<<endl;
    
    return 0;
}

发表于 2022-05-29 15:15:47 回复(0)
import java.util.*;

/**
 * @Title: Move
 * @auth: J
 * @date: 2022/5/24 13:17
 * @Description:
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String all = sc.next();
        String[] steps = all.split(";");
        List<String> directions = new ArrayList<>();
        directions.add("W");
        directions.add("A");
        directions.add("S");
        directions.add("D");
        Integer x = 0;
        Integer y = 0;
                // 过滤掉非法数据
        for (String step : steps) {
            if (step.length() < 2 || step.length() > 3) {
                continue;
            }
            String direction = step.substring(0, 1); // 方向
            try {
                Integer len = Integer.parseInt(step.substring(1)); // 步长
                if (!directions.contains(direction) || len < 0) {
                    continue;
                }
                switch (direction) {
                    case "W":
                        y += len;
                        break;
                    case "S":
                        y -= len;
                        break;
                    case "D":
                        x += len;
                        break;
                    case "A":
                        x -= len;
                        break;
                }
            } catch (NumberFormatException e) { // 如果步长非法,跳过
                continue;
            }
        }
        System.out.println(x + "," + y);
    }
}

发表于 2022-05-24 13:29:27 回复(0)
import re

lst = input().split(';')
x,y = 0,0
for s in lst:
    if 2 <= len(s) <= 3:
        # 判断是否为有效的字符串
        a,b = s[0],s[1:]
        if re.fullmatch(r'[A-Z]',a) and (re.fullmatch(r'\d{2}', b)&nbs***bsp;re.fullmatch(r'\d{1}', b)):
            b = int(b)
            if a == 'A':
                x -= b 
            elif a == 'S':
                y -= b 
            elif a == 'W':
                y += b 
            elif a == 'D':
                x += b 
print('%d,%d'%(x,y))


发表于 2022-05-21 00:10:33 回复(0)
这里可以用stream流解决解决;分号断续输入,然后再用正则表达式解决子字符串匹配问题。(代码很短,但是时间很长)
#include <bits/stdc++.h>
using namespace std;
int main() {
  string n;
    while(cin>>n)
    {string t;pair<int,int> p (0,0);
        stringstream ss(n); 
        while(getline(ss,t,';'))
        {
            if(regex_match(t,regex("^A[0-9]*"))) p.first-=stoi(t.substr(1));  
            else if(regex_match(t,regex("^D[0-9]*"))) p.first+=stoi(t.substr(1));
            else if(regex_match(t,regex("^W[0-9]*")))  p.second+=stoi(t.substr(1));
            else if(regex_match(t,regex("^S[0-9]*")))  p.second-=stoi(t.substr(1));
            else continue;
        }
     cout<<p.first<<","<<p.second<<endl;
    }
    return 0;
}


发表于 2022-04-12 20:19:19 回复(1)
#include <iostream>
#include <vector>


int main() {
    int x = 0, y = 0;
    char tmp;
    //0 normal, -1 waste, 1 wait for num1, 2 wait for num2&nbs***bsp;end, 3 wait for end
    int state = 0;
    int direction = -1, bias = 0;
    std::vector<std::vector<int>> aim = { {0, 1}, {-1, 0}, {0, -1}, {1, 0} };
    while (std::cin.get(tmp))
    {
        if (tmp == '\n')
        {
            break;
        }
        switch (state)
        {
            case -1:
                switch (tmp)
                {
                    case ';' :
                        state = 0;
                        break;
                    default :
                        break;
                }
                break;
            case 0 :
                bias = 0;
                switch (tmp)
                {
                    case ';' :
                        state = 0;
                        break;
                    case 'W' :
                        direction = 0;
                        state = 1;
                        break;
                    case 'A':
                        direction = 1;
                        state = 1;
                        break;
                    case 'S':
                        direction = 2;
                        state = 1;
                        break;
                    case 'D':
                        direction = 3;
                        state = 1;
                        break;
                    default :
                        state = -1;
                        break;
                }
                break;
            case 1:
                switch (tmp)
                {
                    case ';':
                        state = 0;
                        break;
                    default:
                        if (tmp <= '9' && tmp >= '0')
                        {
                            bias = bias * 10 + tmp - '0';
                            state = 2;
                        }
                        else
                        {
                            state = -1;
                        }
                        break;
                }
                break;
            case 2:
                switch (tmp)
                {
                case ';':
                    x += aim[direction][0] * bias;
                    y += aim[direction][1] * bias;
                    state = 0;
                    break;
                default:
                    if (tmp <= '9' && tmp >= '0')
                    {
                        bias = bias * 10 + tmp - '0';
                        state = 3;
                    }
                    else
                    {
                        state = -1;
                    }
                    break;
                }
                break;
            case 3:
                switch (tmp)
                {
                case ';':
                    x += aim[direction][0] * bias;
                    y += aim[direction][1] * bias;
                    state = 0;
                    break;
                default:
                    state = -1;
                    break;
                }
                break;
        }
        
    }
    std::cout << x << ',' << y;

    return 0;
}
状态机之状态转移大法。
发表于 2022-04-12 11:16:00 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        getCoordinate(str);
    }

    private static void getCoordinate(String str) {
        int x = 0, y = 0;
        String[] strings = str.split(";");
        for (String s : strings) {
            if (s.length()<2)
                continue;
            if ((s.charAt(0) == 'A' || s.charAt(0) == 'W' || s.charAt(0) == 'S' || s.charAt(0) == 'D') && isNum(s.substring(1))) {
                if (s.charAt(0) == 'A')
                    x = x - Integer.parseInt(s.substring(1));
                if (s.charAt(0) == 'D')
                    x = x + Integer.parseInt(s.substring(1));
                if (s.charAt(0) == 'W')
                    y = y + Integer.parseInt(s.substring(1));
                if (s.charAt(0) == 'S')
                    y = y - Integer.parseInt(s.substring(1));
            }
        }
        System.out.println(x + "," + y);
    }

    public static boolean isNum(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (!Character.isDigit(s.charAt(i)))
                return false;
        }
        return true;
    }
}

发表于 2022-03-06 10:46:10 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] strs = str.split(";");
        int x=0;
        int y=0;
        for(String s:strs){
            if(s.startsWith("A") && s.substring(1).matches("[0-9]{1,2}")){
               x =  x - Integer.parseInt(s.substring(1));
            }else if(s.startsWith("D") && s.substring(1).matches("[0-9]{1,2}")){
               x =  x + Integer.parseInt(s.substring(1));
            }else if(s.startsWith("S") && s.substring(1).matches("[0-9]{1,2}")){
               y =  y - Integer.parseInt(s.substring(1));
            }else if(s.startsWith("W") && s.substring(1).matches("[0-9]{1,2}")){
               y =  y + Integer.parseInt(s.substring(1));
            }else{
                continue;
            }
        }
        System.out.println( x + "," + y);
    }
}
发表于 2022-03-04 22:22:05 回复(0)
#include<stdio.h>
#include<string>
#include<iostream>

using namespace std;
int main(){
    string strs;
    int x = 0;
    int y = 0;
    getline(cin,strs);
    for(int i =0; i< strs.length();i++){
        if(strs[i] == ';'){   //如果读取到;分隔符
            int j =i-1;
            int len = 0;
            int step = 0;
            while(strs[j]!=';' && j>=0) {//计算这一段的位移是两位数还是三位数
                j--;
                len++;
            }
            if(len==3) step =(strs[i-2]-48)*10+(strs[i-1]-48); //三位     
            else if(len==2) step =strs[i-1]-48;  //两位
            //判断输入是否合法
            if((strs[i-1] >='0'&&strs[i-1] <='9')&&(strs[i-len] >='A'&&strs[i-len] <='Z')){
                //判断方向
                if(strs[i-len] == 'A') x = x-step; 
            else if (strs[i-len] == 'D') x = x+step;
            else if (strs[i-len] == 'S') y = y-step;
            else if (strs[i-len] == 'W') y = y+step;
                
            }
        }
        }
        cout<<x<<','<<y<<endl;
    }

发表于 2022-02-27 09:54:05 回复(0)
// 2021-12-16
// cpp 选手
#include <iostream>
#include <string>
#include <sstream>
#include <set>

using namespace std;

set<char> gValidOP{'A', 'D', 'W', 'S'};
 
struct Point{
    int x;
    int y;
    Point(int xx = 0, int yy = 0):x(xx), y(yy){}
    Point(const Point& other)
    {
        this->x = other.x;
        this->y = other.y;
    }
    Point& operator=(const Point& other)
    {
        this->x = other.x;
        this->y = other.y;
        return *this;
    }
};

class CPosCalculator
{
public:
    CPosCalculator(Point po = Point(0, 0)) : m_pos(po), m_op(0)
    {
    }
    int ParseValidOp(const string& strOp)
    {
        // -1: 无效; 0: 无影响; 1: 有效,需要处理;
        int iRet = 0;
        bool bFirstValid = false;
        bool bSecondValid = true;
        if(!strOp.size()) return iRet;
        for(int i = 0; i < strOp.size(); ++i)
        {
            if(i==0)
            {
                // 第一个字符是否为有效操作
                if(gValidOP.count(strOp[i]))
                {
                    bFirstValid = true;
                    if(strOp[i]=='A')
                    {
                        m_op = -1;
                    }
                    else if(strOp[i]=='D')
                    {
                         m_op = 1;
                    }
                    else if(strOp[i]=='W')
                    {
                         m_op = 2;
                    }
                    else
                    {
                         m_op = -2;
                    }
                } 
                else
                {
                    iRet = -1;
                    bSecondValid = false;
                    break;
                }
            }
            else if(bFirstValid)
            {
                bSecondValid &= isdigit(strOp[i]);
            }
        }
        if(bSecondValid)
        {
            iRet = 1;
            m_offset = atoi(strOp.substr(1).c_str());
        }
        else
            iRet = -1;
        return iRet;
    }
    void Move()
    {
        switch(m_op)
        {
            case -1:
                m_pos.x -= m_offset;
                break;
            case 1:
                m_pos.x += m_offset;
                break;
            case -2:
                m_pos.y -= m_offset;
                break;
            case 2:
                m_pos.y += m_offset;
                break;
        }
    }
    Point& GetPos()
    {
        return m_pos;
    }
private:
    Point m_pos;
    int   m_op;
    int   m_offset;
};

int main()
{
    string strIn;
    while(getline(cin, strIn))
    {
        string strEle;
        CPosCalculator calc;
        int idx_off = 0;
        int idx = -1;
        do
        {
            idx = strIn.find_first_of(';', idx_off);
            strEle = strIn.substr(idx_off, idx - idx_off);
            int op = 0;
            if((op = calc.ParseValidOp(strEle)) == 1)
            {
               calc.Move();
            }
            idx_off += (idx-idx_off + 1);
        }while(idx != -1);
        Point& pp = calc.GetPos();
        cout << pp.x << "," << pp.y << endl;
    }
    return 0;
}

发表于 2021-12-16 14:01:37 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            int[] point = new int[2];
            move(point, str);
            System.out.println(point[0] + "," + point[1]);
        }
    }

    // 坐标移动
    public static void move(int[] point, String str) {
        String[] arr = str.split(";");
        for (String s : arr) {
            if (isOk(s)) {
                char direction = s.charAt(0);
                int size = Integer.parseInt(s.substring(1));
                switch (direction) {
                    case 'A':
                        point[0] -= size;
                        break;
                    case 'S':
                        point[1] -= size;
                        break;
                    case 'D':
                        point[0] += size;
                        break;
                    case 'W':
                        point[1] += size;
                }
            }
        }
    }

    // 判断是否合法
    public static boolean isOk(String str) {
        if (str.length() < 2 || str.length() > 3) {
            return false;
        }
        char temp;
        for (int i=0; i<str.length(); i++) {
            temp = str.charAt(i);
            if (i == 0) {
                if (temp != 'A' && temp != 'S' && temp != 'D' && temp != 'W') {
                    return false;
                }
                continue;
            }
            if (temp < '0' || temp > '9') {
                return false;
            }
        }
        return true;
    }
}

发表于 2021-11-07 14:17:08 回复(0)
while True:
    try:
        n = input().split(";")
        coords = [0, 0]
        dic = {"A": [-1, 0], "D": [1, 0], "W": [0, 1], "S": [0, -1]}
        for i in n:
            if len(i)>=2:
                if (i[0] in dic) and i[1:].isdigit():
                    temp = [j * int(i[1:]) for j in dic[i[0]]]
                    coords = [x + y for x, y in zip(temp, coords)]
        print(str(coords[0]) + "," + str(coords[1]))
    except:
        break


发表于 2021-11-07 01:55:24 回复(0)
    这道题的思路有以下几个步骤:
    1.用strtok函数将字符串进行分割,分隔符为";"
    2.对于分割得到的字符串进行处理,首先是要判断它的有效性。如果分割出来的字符串长度小于2的话,说明是无效的子字符串;如果str[1]~str[len-1]有非数字的字符,那也可以判断为无效的子字符串
    3.接着就根据str[0]的值来进行具体的坐标移动操作,用atoi函数将&str[1]开始的字符串转换为数字
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
    int x;
    int y;
}tCoord;

void calculate(char *str, tCoord *coord)
{
    int len = strlen(str);
    if(len<2)
        return;
    for(int i=1; i<len; i++)
    {
        if(str[i]<'0' || str[i]>'9')
            return;
    }
    
    switch(str[0])
    {
        case 'A':
            coord->x -= atoi(&str[1]);
            break;
        case 'D':
            coord->x += atoi(&str[1]);
            break;
        case 'W':
            coord->y += atoi(&str[1]);
            break;
        case 'S':
            coord->y -= atoi(&str[1]);
            break;
        default:
            break;
    }
}
int main() {
    char str[10000]={0};
    char *p;
    char *delim = ";";
    tCoord coord;
    coord.x = 0;
    coord.y = 0;
    
    scanf("%s", str);
    p = strtok(str, delim);
    while (p) 
    { 
        calculate(p, &coord);
        p = strtok(NULL, delim);
    }
    printf("%d,%d\n", coord.x, coord.y);
    return 0;
}


发表于 2021-10-09 14:45:45 回复(0)
#include<stdio.h>
#include<string.h>
int main(){
    char str[20000]={0};
    int x=0,y=0,num;
    gets(str);
    int l=strlen(str);
    for(int i=0;i<l;i++){
        if(str[i]==';'&&(str[i-4]==';'||str[i-4]==NULL)){
            if(str[i-2]>='0'&&str[i-2]<='9'&&str[i-1]>='0'&&str[i-1]<='9'){
                num = (str[i-2]-48)*10+str[i-1]-48;
            if(str[i-3]=='A')
                x-=num;
            else if(str[i-3]=='D')
                x+=num;
            else if(str[i-3]=='W')
                y+=num;
            else if(str[i-3]=='S')
                y-=num;
            }
        }
        if(str[i]==';'&&(str[i-3]==';'||str[i-3]==NULL)){
            if(str[i-1]>='0'&&str[i-1]<='9'){
                num = str[i-1]-48;
                if(str[i-2]=='A')
                x-=num;
            else if(str[i-2]=='D')
                x+=num;
            else if(str[i-2]=='W')
                y+=num;
            else if(str[i-2]=='S')
                y-=num;
            }
        }
    }
    printf("%d,%d",x,y);
}

发表于 2021-09-18 21:20:01 回复(0)
#include <bits/stdc++.h>
using namespace std;





int main(){
    /*
    下面是一个简单的例子 如:A10;S20;W10;D30;X;A1A;B10A11;;A10;
    输入描述:一行字符串
    输出描述:最终坐标,以逗号分隔
    */
    //分别定义横纵坐标,读取字符串,若读到分号,对临时字符串进行解析
    //长度小于2或大于3的直接抛弃;第一个字母非...,直接抛弃;除第一个字母外,其余位置存在字母的,直接抛弃;
    //A:横坐标减操作;D:横坐标加操作;W:纵坐标加操作;S:纵坐标减操作
    string inputStr;
    while(cin >> inputStr){
        int m = 0 , n = 0;
        string tempStr;
        for(int i = 0; i < inputStr.size(); i++){
            if(inputStr[i] == ';'){
                int len = tempStr.size();
                if(len < 2 || len > 3) tempStr = "";
                if(tempStr[0] != 'A' && tempStr[0] != 'D' && tempStr[0] != 'W' && tempStr[0] != 'S') tempStr = "";
                int sum = 0;
                for(int i = 1; i < tempStr.size(); i++){//临时字符串不为空,才会进来
                    if(tempStr[i] >= '0' && tempStr[i] <= '9') sum += (tempStr[i] - '0') * pow(10,(tempStr.size() - i - 1));
                    else{
                        tempStr = "";
                        break;
                    }
                }
                if(tempStr[0] == 'A') m -= sum;
                if(tempStr[0] == 'D') m += sum;
                if(tempStr[0] == 'W') n += sum;
                if(tempStr[0] == 'S') n -= sum;
                tempStr = "";
            }
            else{
                tempStr += inputStr[i];
            }
        }
        cout << m << "," << n << endl;
    }
    return 0;
}

发表于 2021-09-07 14:45:39 回复(0)
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
    string str,strKey;
    int x=0,y=0;
    cin >> str;
    while(str.find(";") != string::npos)
    {
          strKey = str.substr(0,str.find(";"));
          if((strKey.length() == 3 && isdigit(strKey[1]) && isdigit(strKey[2])) ||
           (strKey.length() == 2 && isdigit(strKey[1]))){
              switch(strKey[0])
              {
                case 'A':
                    x-=atoi(str.substr(1).c_str());
                    break;
                case 'D':
                    x+=atoi(str.substr(1).c_str());
                    break;
                case 'S':
                    y-=atoi(str.substr(1).c_str());
                    break;
                case 'W':
                    y+=atoi(str.substr(1).c_str());
                    break;        
              }
         }
             str = str.substr(str.find(";")+1);
    }
      cout<< x <<"," << y<< endl;
    return 0;
}

发表于 2021-09-06 13:11:13 回复(0)