给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//这种简单的策略只能构造一些简单的没有嵌套的[],只要有嵌套立刻炸
class Solution {
public:
string decodeString(string s) {
string ans = "";
int len = s.length();
int count;
for(int i = 0; i < len; ++i)
{
if(s[i]>='1' && s[i] <= '9')
{
count = s[i] - '0';
}
else if(s[i]=='[')
{
string buff = "";
while(++i < len && s[i]!=']')
{
buff += s[i];
}
for(int j = 0; j < count; ++j)
{
ans += buff;
}
}
else
ans += s[i];
}
return ans;
}
};
想到了逆波兰表达式:但是后面考虑了一下还是没办法处理啊(嵌套部分处理好了,但是还有不嵌套的的呀
class Solution {
public:
string re()
{
string ans = "";
return ans;
}
string decodeString(string s) {
string ans = "";
int len = s.length();
vector<int>buffn;buff.clear();
vector<string>buffc;bugg.clear();
for(int i = 0; i < len; ++i)
{
//遇到是数字
if(s[i]>='1' && s[i] <= '9')
{
string str_num = "";
//之前没有考虑到数字可能是多位的
while(i < len && s[i]>='1' && s[i] <= '9')
{
str_num += s[i];
i++;
}
if(str_num != "")
buffn.push_back(stoi(str_num));
}
else if(s[i] == '[')
{
string str_c = "";
while(i < len && s[i]>='a' && s[i] <= 'z' || s[i]>='A' && s[i] <= 'Z')
{
str_c += s[i];
i++;
}
if(str_c != "")
{
buffc.push_back(str_c);
}
}
}
return ans;
}
};
后面还是回到了递归:
class Solution {
public:
string re(string str)
{
string buff = "";
int flag = 0;
for (int i = 0; i < str.length();)
{
if (str[i] >= '0' && str[i] <= '9')
{
string str_num = "";
//之前没有考虑到数字可能是多位的
while (i < str.length() && str[i] >= '0' && str[i] <= '9')
{
str_num += str[i];
i++;
}
if (str_num != "")
{
flag = stoi(str_num);
}
}
else if (str[i] == '[')
{
int count = 1, counts = 0;
for (int j = i + 1; j < str.length(); ++j)
{
if (str[j] == '[')
count++;
else if (str[j] == ']')
counts++;
if (count == counts)
{
string t = re(str.substr(i + 1, j - i - 1));
for (int k = 0; k < flag; ++k)
{
buff += t;
}
flag = 0;
i = j + 1;
break;
}
}
}
else
buff += str[i++];
}
return buff;
}
string decodeString(string s) {
int len = s.length();
string ans = "";
int flag = 0;
for (int i = 0; i < len;)
{
//遇到是数字
if (s[i] >= '0' && s[i] <= '9')
{
string str_num = "";
//之前没有考虑到数字可能是多位的
while (i < len && s[i] >= '0' && s[i] <= '9')
{
str_num += s[i];
i++;
}
if (str_num != "")
flag = stoi(str_num);
}
else if (s[i] == '[')
{
int count = 1, counts = 0;
for (int j = i + 1; j < len; ++j)
{
if (s[j] == '[')
count++;
else if (s[j] == ']')
counts++;
if (count == counts)
{
string t = re(s.substr(i + 1, j - i - 1));
for (int k = 0; k < flag; ++k)
{
ans += t;
}
flag = 0;
i = j + 1;
break;
}
}
}
else
ans += s[i++];
}
return ans;
}
};
看到题解里面还是有按照栈的办法处理的,但是不想看了,因为栈和递归的思想本质上差不多