题意:给定一个“编码”过的字符串,现将其解码; 解码规则:根据数字+字符串的形式将其完全展开即可 传送门
输入:s = “3[a]2[bc]” 输出:“aaabcbc”
题解:栈
string decodeString(string s) {
vector<string> stk;
int ptr = 0;
while (ptr < s.size()) {
char cur = s[ptr];
if (isdigit(cur)) {
string digits;
while (isdigit(s[ptr]))
digits += s[ptr++];
stk.push_back(digits);
}
else if (isalpha(cur) || cur == '[') {
stk.push_back(string(1, s[ptr++]));
}
else {
++ptr;
string res;
while (1) {
res = stk.back() + res;
stk.pop_back();
if (stk.back() == "[") {
stk.pop_back();
break;
}
}
int repTime = stoi(stk.back());
stk.pop_back();
string tmp;
while (repTime--) tmp += res;
stk.push_back(tmp);
}
}
string ret;
for (auto &t : stk) ret += t;
return ret;
}
|