394. Decode String
这题花了不少时间,明明是考察栈的知识,用stack或者手写递归就行,我就是半天写不出,想起来之前有一道写什么miniparse的题还是最长文件路径的题,还有这类解析什么的题,反正自己写的代码比较丑,贴出来吧。
class Solution {
public:
string work(string s, int &x, int n) {
if(x > n) return "";
int t = 0;
string s1 = "";
int tag1 = x;
while(x < n && !isdigit(s[x])) x++;
s1 = s.substr(tag1, x - tag1);
if(x == n) return s1;
while(x < n && isdigit(s[x])) {
t = t * 10 + s[x] - '0'; x++;
}
if(s[x] == '[') {
x++;
int id = x;
while(x < n && !isdigit(s[x]) && s[x] != ']') x++;
if(s[x] == ']') {
string t1 = "", t2 = s.substr(id, x - id);
for (int i = 0; i < t; i++) t1 += t2;
x++;
if(x == n) return s1 + t1;
if(x < n) {
//cout << "t1 " << x << endl;
if(s[x] == ']') return s1 + t1;
else return s1 + t1 + work(s, x, n);
}
} else {
//cout << "td " <<x <<endl;
string t0 = s.substr(id, x - id);
//cout << "asd " << x << endl;
string t1 = "", t2 = work(s, x, n);
//cout << t0 << " test " << t2 << " " << x << endl;
t2 = t0 + t2;
for (int i = 0; i < t; i++) t1 += t2;
x++;
//cout << x<< " " <<t1 << endl;
if(x == n) return s1 + t1;
else {
if(s[x] == ']') return s1 + t1;
return s1 + t1 + work(s, x, n);
}
}
}
return "";
}
string decodeString(string s) {
int x = 0;
return work(s, x, s.size());
}
};