题目:Given an encoded string, return it’s decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].
Examples:
s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.
这道题采用深搜的思想,用递归完成,当遇到字母时,直接加到结果字符串中,如果是数字,则用变量num记录数字,当遇到左括号时,调用递归函数,实现深搜,当遇到右括号时,返回括号中字符串解码结果。代码如下:
class Solution {
public:
string decode(string s, int &k) {
string res = "";
int num = 0;
while(k < s.size() ) {
if(s[k] >= 'a' && s[k] <= 'z') {
res += s[k];
k++;
}
if(s[k] >= '0' && s[k] <= '9') {
num = num*10+(s[k]-'0');
k++;
}
else if(s[k] == '[') {
k++;
string t = decode(s, k);
for(int i = 0; i < num; i++) {
res += t;
}
num = 0;
}
else if(s[k] == ']') {
k++;
return res;
}
}
return res;
}
string decodeString(string s) {
int k = 0;
return decode(s, k);
}
};