题目:
例子:ab2[cd3[ef]], 用人脑是怎么读的?
- 外层结构
ab + 2[ ... ]
- 内层
cd + 3[ef]
- 最里面
ef
关键点:每一层 […] 都是一个 独立子问题, 这个表达式本质是:
decode(s) = 前缀 + k * decode(子串)
当我们遇到 [ 的时候,必须保存状态:
总结一句话:
遇到 [ 就压栈保存现场,遇到 ] 就出栈恢复现场
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <stack> #include <string>
using std::stack; using std::string;
class Solution { public: string decodeString(string s) { stack<int> times; stack<string> strs;
string curr = ""; int num = 0, k;
for (char ch : s) { if (ch >= '0' && ch <= '9') { num = num * 10 + (ch - '0'); } else if (ch == '[') { times.push(num); strs.push(curr); num = 0; curr = ""; } else if (ch == ']') { k = times.top(); times.pop(); string prev = strs.top(); strs.pop();
string tmp; for (int i = 0; i < k; i++) tmp += curr;
curr = prev + tmp; } else { curr += ch; } }
return curr; } };
#include <iostream> int main() { Solution S; string s1 = "2[abc]3[cd]ef"; string s2 = "3[a2[c]]"; string s3 = "2[2[y]pq]";
std::cout << S.decodeString(s1) << '\n';
std::cout << S.decodeString(s2) << '\n';
std::cout << S.decodeString(s3) << '\n'; }
|