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".
class Solution {
public:
string decodeString(string s) {
int pos = 0;
return helper(pos, s);
}
string helper(int &pos, string s){
int num = 0;
string word = "";
for(;pos<s.size(); pos++)
{
char cur = s[pos];
if(cur == '[')
{
string curStr = helper(++pos, s);
for(; num>0; num--) word += curStr;
}else if(cur >= '0' && cur <= '9')
{
num = num*10 + cur - '0';
}else if(cur == ']')
return word;
else
word += cur;
}
return word;
}
};
字符串解码算法
本文介绍了一种用于解码特定格式字符串的算法。该算法能够处理形如 k[encoded_string] 的编码规则,其中 encoded_string 会被重复 k 次。通过递归方式解析嵌套的括号和数字,最终返回解码后的字符串。
788

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



