目录
一、题目描述
二、算法原理
三、代码实现
cpp
class Solution {
public:
string decodeString(string s)
{
stack<string> s1;
s1.push("");
stack<int> s2;
int i = 0, n = s.size();
while (i < n)
{
//1.如果是数字入数字栈
if (s[i] >= '0' && s[i] <= '9')
{
int sum = 0;
while (s[i] >= '0' && s[i] <= '9')
{
int val = s[i] - '0';
sum = sum * 10 + val;
i++;
}
s2.push(sum);
}
//2.如果是[ 统计后面的字符串入字符串栈
else if (s[i] == '[')
{
string str;
i++;
while (s[i] >= 'a' && s[i] <= 'z') str += s[i++];
s1.push(str);
}
//3.如果是] 解码后入字符栈顶的子串后面
else if (s[i] == ']')
{
int times = s2.top();
s2.pop();
string temp = s1.top();
s1.pop();
while (times--) s1.top() += temp;
i++;
}
//4.如果是字符 把字符串入栈顶的子串后面
else if (s[i] >= 'a' && s[i] <= 'z')
{
string str;
while (s[i] >= 'a' && s[i] <= 'z') str += s[i++];
if (str.size() > 0) s1.top() += str;
}
}
return s1.top();
}
};