题目: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);
}
};
本文介绍了一种基于递归的字符串解码算法,该算法能够处理形如 k[encoded_string] 的编码格式,其中 encoded_string 会被重复 k 次。通过使用深搜思想,文章详细解释了如何解析输入字符串,并提供了 C++ 代码实现。
1352

被折叠的 条评论
为什么被折叠?



