1 解题思想
意思是在字符串当中,有一个特殊的格式 — k[S],遇到这种状况,需要把S重复k次,注意是可以嵌套的
在这次解题当中,我是使用了栈的方式,去解决这个问题。分别使用了一个全局的已解码的字符串Builder,另外对于为解码的,使用栈来暂存。
符号’[‘控制进栈,分别进入计数数字和之前尚未解码的字符串
符号’]’控制出站,出栈当前计数,并且将未解码的字符串进行重复,再链接上一个未解码的字符串
注意栈空的时候证明当前嵌套解码完毕,需要添加到全局当中,反之基于暂存。
2 原题
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
3 AC解
public class Solution {
public String decodeString(String s) {
int n = s.length();
char[] ss = s.toCharArray();
Stack<Integer> counts = new Stack<Integer>();
Stack<String> strings = new Stack<String>();
StringBuilder result = new StringBuilder();
int count = 0;
//当前需要解码,但是还没有遇到]暂存的
String currentString = "";
for(int i=0;i<n;i++){
if(ss[i]>='0' && ss[i]<='9'){
count = count * 10;
count = count + ss[i] -'0';
} else if(ss[i] == '['){
counts.push(count);
count = 0;
strings.push(currentString);
currentString = "";
}else if(ss[i] >='a' && ss[i]<='z'){
//注意栈空与否很重要
if(!counts.isEmpty())
currentString += ss[i];
else result.append(ss[i]);
} else if(ss[i] == ']'){
int times = counts.pop();
if(counts.isEmpty()){
for(int j=0;j<times;j++)
result.append(currentString);
currentString=strings.pop();
} else {
String tmp = "";
for(int j=0;j<times;j++)
tmp+=currentString;
currentString = strings.pop()+tmp;
}
}
}
return result.toString();
}
}
LeetCode 394: 使用栈解码字符串
本文介绍了LeetCode 394题的解题思路,重点是利用栈来解决字符串的解码问题。解题过程中,遇到'['时,将数字和未解码字符串压入栈中;遇到']'时,将栈顶数字与未解码字符串拼接并重复栈顶数字次,然后连接到全局解码字符串。解析过程中注意栈空的条件,标志着当前嵌套解码完成。
270

被折叠的 条评论
为什么被折叠?



