Leetcode 394.字符串编码

字符串编码

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: 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".

求解

本题中明显有括号的匹配问题,因此需要使用栈来求解。当碰到右括号(])时,字符串出栈,碰到左括号([)时,保存左右括号内的字符串([]),继续出栈,保存字符串重复次数,直至栈为空或碰到非数字。要注意重复次数不是个位数,将字符串重复之后压入栈中。继续处理剩余字符串,同样执行上述过程,直至处理完字符串。然后将栈中所有的字符出栈构成结果字符串返回。

 import java.util.Stack;

 public class Solution{
public String decodeString(String s){
int n=s.length();
Stack<Character> stack=new Stack<Character>();
String result="";
String temp="";
for(int i=0;i<n;i++){
char str=s.charAt(i);
if(str!=']'){
stack.push(str);
}else{
char ch=stack.pop();
while(ch!='['){
temp=ch+temp;
ch=stack.pop();
}
String times="";
while(!stack.isEmpty()){
ch=stack.pop();
if(Character.isDigit(ch)){
times=ch+times;
}else{
stack.push(ch);
break;
}
}
for(int j=0;j<Integer.parseInt(times);j++){
for(int k=0;k<temp.length();k++){
stack.push(temp.charAt(k));
}
}
temp="";
}
}
while(!stack.isEmpty()){
result=stack.pop()+result;
}
return result;
}
}
上一篇:[LeetCode] Decode String 解码字符串


下一篇:Leetcode中字符串总结