# 字符串解码

LeetCode算法网站题目

https://leetcode-cn.com/problems/decode-string/

1.递归

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--;
}
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);
}
};

2.单栈解法

class Solution
{
private:
stack<char>Char_In_stack;
void Double_The_String(string&s,int k)
{
string w=s;
int i;
for(i=0; i<k-1; i++)
s=s+w;
}
void Get_into_Stack(string&s)
{
for(int i=0; i<s.size(); i++)
Char_In_stack.push(s[i]);
}
public:
string decodeString(string s)
{
int i;
int len=s.size();
string tool;
int k;
int nums;
for(i=0; i<len; i++)
{
if(s[i]==']')
{
k=0;
nums=1;
tool="";
while(Char_In_stack.top()!='[')
{
tool=Char_In_stack.top()+tool;
Char_In_stack.pop();
}
Char_In_stack.pop();
while(!Char_In_stack.empty()&&Char_In_stack.top()<='9'&&Char_In_stack.top()>='0')
{

k=k+(Char_In_stack.top()-'0')*nums;
nums=nums*10;
Char_In_stack.pop();
}
Double_The_String(tool,k);
Get_into_Stack(tool);
}
else
{
Char_In_stack.push(s[i]);
}
}
tool="";
while(!Char_In_stack.empty())
{
tool=Char_In_stack.top()+tool;
Char_In_stack.pop();
}
return tool;
}
};

3.双栈解法————代码极其乱！！！！！

class Solution
{
public:
string getDigits(string &s, size_t &ptr)
{
string ret = "";
while (isdigit(s[ptr]))
{
ret.push_back(s[ptr]);
ptr++;
}
return ret;
}

string getString(vector <string> &v)
{
string ret;
for (const auto &s: v)
{
ret += s;
}
return ret;
}

string decodeString(string s)
{
vector <string> stk;
size_t ptr = 0;

while (ptr < s.size())
{
char cur = s[ptr];
if (isdigit(cur))
{
// 获取一个数字并进栈
string digits = getDigits(s, ptr);
stk.push_back(digits);
}
else if (isalpha(cur) || cur == '[')
{
// 获取一个字母并进栈
stk.push_back(string(1, s[ptr++]));
}
else
{
++ptr;
vector <string> sub;
while (stk.back() != "[")
{
sub.push_back(stk.back());
stk.pop_back();
}
reverse(sub.begin(), sub.end());
// 左括号出栈
stk.pop_back();
// 此时栈顶为当前 sub 对应的字符串应该出现的次数
int repTime = stoi(stk.back());
stk.pop_back();
string t, o = getString(sub);
// 构造字符串
while (repTime--)
t += o;
// 将构造好的字符串入栈
stk.push_back(t);
}
}

return getString(stk);
}
};


• 0
点赞
• 1
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

07-06 1906
07-01 1153

04-01 289
05-07 242
02-01 1075
08-22 2485
04-13 2290
04-18 896
10-29 7065
04-22 4266
©️2020 CSDN 皮肤主题: 1024 设计师:白松林

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。