1078 字符串压缩与解压 解题代码测试结果问题整理 解题代码 #include<iostream> #include<string> #include<vector> #include<cctype> using namespace std; vector<pair<char, int>> v; void compress(string str) { int len = str.length(); for (int i = 0; i < len; i++) { if (!i || str[i] != str[i - 1]) { v.push_back(make_pair(str[i],1)); } else v.back().second++; } for (auto x : v) { if (x.second != 1) cout << x.second; cout << x.first; } } void decompress(string str) { int len = str.length(); for (int i = 0; i < len; i++) { if (isalpha(str[i]) || str[i] == ' ') cout << str[i]; else { int pos = i; while (isdigit(str[pos++])) {}; pos -= 2; int cnt = stoi(str.substr(i, pos - i + 1)); for (int j = 0; j < cnt; j++) cout << str[pos + 1]; i = pos + 1; } } } int main() { char c; string str; cin >> c; getchar(); getline(cin, str); if (c == 'C') compress(str); else decompress(str); return 0; } 测试结果 问题整理 1.基础题目。 2.明白了make_pair()的用法,等同于<>。