给定一个编码字符串,返回它的解码字符串。
编码规则是: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”。
解决方法1:堆栈
- 如果遇到数字num,代表要重复接下来的 [ ] 的内容num次数,把它存入operate堆栈中
- 如果遇到 ‘ [ ’ ,那么需要把之前已经读取的内容存到堆栈strStack中,并且用result来记录接下来要重复的内容
- 如果遇到字母,就把它存入当前结果中
- 如果遇到 ‘ ] ’ ,那么代表要把当前result中的内容重复operate.pop()次,重复后与之前已经读取的最相近的strStack中内容结合起来
class Solution {
public String decodeString(String s) {
if(s == null || s.length() == 0) return "";
int len = s.length();
Stack<Integer> operate = new Stack<Integer>();
Stack<String> strStack = new Stack<String>();
int i = 0;
String result = "";
l:while(i < len)
{
int num =0;
while(s.charAt(i) <= '9' && s.charAt(i) >= '0')
{
num = num*10 + s.charAt(i)-'0';
i++;
}
if(num>0)operate.add(num);
if(s.charAt(i) == '[')
{
strStack.push(result);
result = "";
i++;
}
while(s.charAt(i) <= 'z' && s.charAt(i) >= 'a')
{
result += s.charAt(i++);
if(i == s.length()) break l;
}
if(s.charAt(i) == ']')
{
String sb = strStack.pop();
int time = operate.pop();
for(int j = 0;j < time;j++)
sb = sb + result;
result = sb;
i++;
}
}
return result;
}
}