遍历字符串时分三种情况讨论当前字符:
1. 若左括号,直接压入栈(该栈主要实现括号匹配即括号内的子串的重复)
2.若右括号,则弹出最近左括号之间的子串,且重复该子串。
3.若为字母,判断是否为重复字母,若是,则重复该字母。
且,对于每次重复完成的串,应判断是否还存在左括号,若存在则当前子串属于要继续被重复的串(内外层括号的情况);
否则,当前串即为结果串的子串,可先加入至结果串。
#include "pch.h" #include<iostream> #include<string> #include<stack> using namespace std; string unCompressed(string s) { stack<string> left; string res, digit, dump,tmp; int len = s.length(); int i = 0, j; while (i < len) { if (s[i] == '(') { //情况一 tmp = s[i]; left.push(tmp); i++; } else if (s[i] == ')') { //情况二 i++; while (i < len && s[i] == 0) { // 删除数字前导的0 i++; } digit = ""; // 一定要先置空 while (i < len && isdigit(s[i])) { // 获取数字 digit += s[i]; i++; } dump = ""; while (left.top() != "(") { // 获取重复的子串 dump = left.top() + dump; // 注意前面的字符串被压入栈底 left.pop(); } left.pop(); // zuokuohao tmp = ""; for (int k = 0;k < stoi(digit);++k) { // 实现重复串 tmp += dump; } if (left.empty()) { res += tmp; } else { left.push(tmp); // 若还有左括号,说明还有重复的子串,继续放入栈中 } } else { // 情况三:字母 j = i++; if (i < len && isdigit(s[i])) { // 重复字母 while (i < len && s[i] == 0) { i++; } while (i < len && isdigit(s[i])) { digit += s[i]; i++; } dump = ""; for (int k = 0;k < stoi(digit);++k) { dump += s[j]; } if (left.empty()) { res += dump; } else { left.push(dump); } } else { //单纯字母,作为结果子串 if (left.empty()) { res += s[j]; } else { tmp = s[j]; left.push(tmp); } } } } return res; } int main() { int n; cin >> n; cout << unCompressed(s) << endl; for (int i = 0;i < n;++i) { string s; cin >> s; cout<<unCompressed(s)<<endl; } return 0; }