1、
2、
3[a]2[bc]
3 num= 3
[ numstack : 3
a cur=a
] 迭代 strstack aaa cur=aaa stack pop
2 num=2
[ numstack : 2
bc strstack.push(cur) cur.clear() strstack aaa
] strstrack aaabcbc
主要思路使用字符串栈来保存结果
3、
class Solution {
public:
string decodeString(string s) {
int len = s.size();
int num = 0;
stack<int> numstack;
stack<string> strstack;
string cur = "";
string result = "";
for(int i = 0;i < len;i++)
{
if(s[i] >='0' && s[i] <= '9')
{
num = 10*num + s[i] - '0';
}
else if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))
{
cur+= s[i];
}
else if(s[i] == '[')
{
numstack.push(num);
num=0;
strstack.push(cur);
cur.clear();
}
else if(s[i] == ']')
{
for(int j = 0;j < numstack.top();j++)
{
strstack.top()+=cur;
}
numstack.pop();
cur = strstack.top();
strstack.pop();
}
}
return cur;
}
};
4、大佬写的递归看起来要简单的多
class Solution {
public:
string analysis(string s, int& index) {
string res;
int num = 0;
string temp;
while (index < s.size()) {
if (s[index] >= '0' && s[index] <= '9') {
num = 10 * num + s[index] - '0';
}
else if (s[index] == '[') {
temp = analysis(s, ++index);//碰到'[',开始递归
while(num-->0) res += temp;
num = 0;//num置零
}
else if (s[index] == ']') break;//碰到']',结束递归
else res += s[index];
index++;
}
return res;
}
string decodeString(string s) {
int index = 0;
return analysis(s, index);
}
};