题目描述
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例 1:
输入:s = “3[a]2[bc]”
输出:“aaabcbc”
示例 2:
输入:s = “3[a2[c]]”
输出:“accaccacc”
示例 3:
输入:s = “2[abc]3[cd]ef”
输出:“abcabccdcdcdef”
示例 4:
输入:s = “abc3[cd]xyz”
输出:“abccdcdcdxyz”
提示:
1 <= s.length <= 30
s 由小写英文字母、数字和方括号 ‘[]’ 组成
s 保证是一个 有效 的输入。
s 中所有整数的取值范围为 [1, 300]
解题思路
遍历一次字符串,当遇到数字、字母时和左中括号时,把字符压入栈中,当遇到右中括号时,将栈中字符一个个取出,直到取完一次数字,要注意中括号前数字可能不止一个字符比如"12"就是要重复12次字符串。完成一次取出操作后,记录取出的数字n和字符串,将字符串重复n次复制后再压入栈中。
代码如下:
class Solution {
public:
string decodeString(string s) {
stack<char> Stack1;
char c1;
int n = s.length();
string::iterator itTest;
for (int i = 0; i < n; i++)
{
if (s[i] == ']')
{
string str1;
while ((!Stack1.empty()) && (Stack1.top() != '['))
{
c1 = Stack1.top();
str1.push_back(c1);
Stack1.pop();
}
//出来的str1是反向的,要给str1倒置
string str3;
string::reverse_iterator it1;
for (it1 = str1.rbegin(); it1 != str1.rend(); it1++)
{
str3.push_back(*it1);
}
if(!Stack1.empty())
{
Stack1.pop(); //去除左中括号
}
if (!Stack1.empty())
{
c1 = Stack1.top(); //现在c1是数字
}
int num = 0;
int x = 1;
while ((c1 - '0' >= 0) && (c1 - '0' <= 9) && !Stack1.empty())
{
int n1 = c1 - '0';
num = n1 * x + num;
x = x * 10;
Stack1.pop();
if (!Stack1.empty())
c1 = Stack1.top();
}
string str2;
//cout << "num:" << num << endl;
while (num != 0)
{
str2.append(str3);
num--;
}
string::iterator it;
for (it = str2.begin(); it != str2.end(); it++)
{
Stack1.push(*it);
}
}
else
{
Stack1.push(s[i]);
}
}
string str4;
while (!Stack1.empty())
{
char c2 = Stack1.top();
str4.push_back(c2);
Stack1.pop();
}
string str5;
string::reverse_iterator it2;
for (it2 = str4.rbegin(); it2 != str4.rend(); it2++)
{
str5.push_back(*it2);
}
return str5;
}
};
代码优化
完成题目后查看答案解析,参考解析的方法重写了一遍该题目。具体思路为创建两个栈stack<int>和stack<string>。方法和上述类似,优化的地方在于,只有一个栈时,取出的元素是倒过来的,这个方法省略了将字符串回正的步骤。
代码如下:
class Solution {
public:
int num = 0;
string str = "";
stack<int> numStack;
stack<string> stringStack;
string decodeString(string s) {
int n = s.size();
for (int i = 0; i < n; i++)
{
if ((s[i] >= '0') && (s[i] <= '9'))
{
num = num * 10 + (s[i] - '0');
}
if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))
{
str = str + s[i];
}
if (s[i] == '[')
{
numStack.push(num);
stringStack.push(str);
num = 0;
str = "";
}
if (s[i] == ']')
{
int num1 = numStack.top();
numStack.pop();
while (num1 != 0)
{
stringStack.top() = stringStack.top() + str;
num1--;
}
str = stringStack.top();//如果之后还是字符串便加在其后面
stringStack.pop();
}
}
return str;
}
};