问题描述:
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]
.
示例:
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) {
return bl(s);
}
string bl(string str)
{
if (str == "") return "";
string res = "";
int count = 0;
int start = -1;
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
if (!count)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
res.append(1, str[i]);
continue;
}
else if (str[i] >= '0' && str[i] <= '9')
{
sum = sum * 10 + str[i] - '0';
continue;
}
}
if (str[i] == '[')
{
if (count == 0) start = i;
count++;
}
else if (str[i] == ']') count--;
if (!count)
{
string st = bl(str.substr(start + 1, i - start - 1));
for (int t = 0; t < sum; t++) res += st;
start = i + 1;
sum = 0;
}
}
return res;
}
};