题解 | #坐标移动#不使用库函数,自己实现各个功能

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29?tpId=37&tqId=21240&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=3&judgeStatus=undefined&tags=&title=

#include <iostream>
#include <string>
#include <vector>
using namespace std;

string legal = "ADWS";  // 方向指令的合法字符
bool find_legal(char a) {
    for (int i = 0; i < 4; i++) {
        if (a == legal[i])
            return true;
    }
    return false;
}

vector<string> first(string input) {//对输入的字符串进行切割
    int input_size = input.size();
    vector<string> result;
    int left = 0;
    for (int right = 0; right < input_size; right++) {
        if (input[right] == ';') {
            
            string now = input.substr(left, right - left);
            if (!now.empty()) {  
                result.push_back(now);
            }
            left = right + 1; 
        }
    }
    return result;
}

vector<string> is_legal(const vector<string>& first) {//判断字符串是否合法,传入first函数处理得到的字符串
    vector<string> result;
    for (const string& command : first) {
        int nums_size = command.size();
        if (nums_size >= 2 && nums_size <= 3) {
            if (find_legal(command[0])) { 
                bool valid = true;
                for (int k = 1; k < nums_size; k++) {
                    if (!(command[k] >= '0' && command[k] <= '9')) {
                        valid = false;
                        break;
                    }
                }
                if (valid) {
                    result.push_back(command); 
                }
            }
        }
    }
    return result;
}

int main() {
    int x = 0, y = 0;
    string input;
    cin >> input;
    vector<string> legal_input = is_legal(first(input));
    for (const string& command : legal_input) {
        int move_cost = command.substr(1).empty() ? 0 : stoi(command.substr(1)); 
        
        if (command[0] == 'A') {
            x -= move_cost; 
        } else if (command[0] == 'D') {
            x += move_cost; 
        } else if (command[0] == 'W') {
            y += move_cost; 
        } else if (command[0] == 'S') {
            y -= move_cost; 
        }
    }
    
    cout << x << ',' << y << endl; 
}

全部评论

相关推荐

点赞 评论 收藏
分享
否极泰来来来来:解约赔多少
点赞 评论 收藏
分享
07-23 15:05
门头沟学院 Java
熊大不大:不好意思KPI数据刚刚刷新,刚刚达标
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
09-09 14:10
大三,在字节实习两周,被同学举报,辅导员要求回学校怎么办?
我的代码出BUG了:方案1:找领导说明情况然后请个假,回去一天找辅导员报道,见完面直接溜 。方案2:给辅导员卖惨,卖惨内容为家里没钱有贷款+没钱吃饭+心理抑郁+不想活了+社会险恶(同学举报)+想一si了之,例如:.....。长线规划:你这个同学的行为太恶心了,一定暗中收集你这个同学的错误事迹。比如举报课程设计不是他自己做的、比如以后他要是考公,你去考场门口拉横幅说他***,就说你是他好朋友,拉横幅只是为了开玩笑
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务