394. 字符串解码
class Solution {
public:
string decodeString(string s) {
string Result;
string TokenCount;
stack<int> Counts;
stack<string> SubStrings;
for (char c : s) {
if (isdigit(c))
TokenCount += c;
if (isalpha(c)) {
// We need to discriminate top-level expressions.
if (Counts.empty())
Result += c;
else
SubStrings.top() += c;
}
// Push one level.
if (c == '[') {
Counts.push(stoi(TokenCount));
SubStrings.emplace();
// Clear TokenCount immediately. Otherwise nested expression would fail.
TokenCount.clear();
}
// Pop one level.
if (c == ']') {
int Repeat = Counts.top();
string Processed;
for (int i = 0; i < Repeat; ++i)
Processed += SubStrings.top();
Counts.pop();
SubStrings.pop();
// Put Processed string onto previous level. Still, we need to check if
// we're at the top level.
if (Counts.empty())
Result += Processed;
else
SubStrings.top() += Processed;
}
}
return Result;
}
};
感觉也没什么好讲的吧。但我是真的不喜欢做这种题目,就是一个很麻烦的力气活——当然,你让我做真算法题我也是做不出来的,那咋办呢。
这里要注意的主要是分开处理顶层表达式,以及「把当前层的字符串合并到上一层」这个操作。这是一个比较自然的递归过程。