Updating a Dictionary UVA - 12504 模拟字符串处理

题目链接

分析:

题目不难,就是map的应用,主要为如何简单的提取字符串中的我们需要的内容。

我是遍历一遍字符串,判断是否为数字或字母来提取,然后存入map中。最后分别遍历两个map,比较即可。

#include <bits/stdc++.h>
using namespace std;
map<string, string> dic;
map<string, string> com_dic;
vector<string> jia;
vector<string> jian;
vector<string> xing;

void init() {
    dic.clear(), com_dic.clear();
    jia.clear(), jian.clear(), xing.clear();
}

void split(string str, int f) {
    for(int i = 0; i < str.length();) {
        string s1,s2;
        while(!isalpha(str[i]) && i<str.length())
            i++;
        while(isalpha(str[i]) && i<str.length()) {
            s1 += str[i]; i++;
        }
        while(!isdigit(str[i]) && i<str.length())
            i++;
        while(isdigit(str[i]) && i<str.length()) {
            s2 += str[i]; i++;
        }
        if(!f) dic[s1] = s2;
        else com_dic[s1] = s2;
    }
}

void compare() {
    for(auto it=dic.begin(); it!=dic.end(); it++) {
        if(!com_dic.count(it->first)) jian.push_back(it->first);
        else {
            if(it->second!=com_dic.find(it->first)->second)
                xing.push_back(it->first);
        }
    }
    for(auto it= com_dic.begin(); it!=com_dic.end(); it++) {
        if(!dic.count(it->first))
            jia.push_back(it->first);
    }
}

void Print(vector<string> vector1) {
    for(int i = 0; i < vector1.size(); i++) {
        if(i==0) cout << vector1[i];
        else cout << "," << vector1[i];
    }
    cout << endl;
}

int main() {
    int n;
    cin >> n;
    string s1, s2;
    while(n--) {
        init();
        cin >> s1 >> s2;
        split(s1,0), split(s2,1);
        compare();
        if(jia.empty() && jian.empty() && xing.empty())
            cout << "No changes" << endl;
        else {
            if(!jia.empty()) { cout << "+"; Print(jia); }
            if(!jian.empty()) { cout << "-"; Print(jian); }
            if(!xing.empty()) { cout << "*"; Print(xing); }
        }
        cout << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43185391/article/details/88088143