DFS思想解决,利用]分割,传递i值比较巧妙得判断了每个重复字符串的结束位置。
class Solution {
public:
string decodeString(string s, int &i) {
string result = "";
string strone;
while(i < s.length() && s[i] != ']') {
if(s[i] < '0' || s[i] > '9')
result += s[i++];
else{
int num = 0;
while(s[i] != '[')
num = num * 10 + (s[i++] - '0');
strone = decodeString(s, ++i);
i++;
while(num--)
result += strone;
}
}
return result;
}
string decodeString(string s) {
int i = 0;
return decodeString(s, i);
}
};