给定一个通过编码的字符串,返回它解码后的字符串。 java
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 git
你能够认为输入字符串老是有效的;输入字符串中没有额外的空格,且输入的方括号老是符合格式要求的。 ide
此外,你能够认为原始数据不包含数字,全部的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。 编码
示例: spa
s = "3[a]2[bc]", 返回 "aaabcbc". code
s = "3[a2[c]]", 返回 "accaccacc". 字符串
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef". string
本题中明显有括号的匹配问题,所以须要使用栈来求解。当碰到右括号(])时,字符串出栈,碰到左括号([)时,保存左右括号内的字符串([]),继续出栈,保存字符串重复次数,直至栈为空或碰到非数字。要注意重复次数不是个位数,将字符串重复以后压入栈中。继续处理剩余字符串,一样执行上述过程,直至处理完字符串。而后将栈中全部的字符出栈构成结果字符串返回。 it
1 import java.util.Stack; 2 3 public class Solution{ 4 public String decodeString(String s){ 5 int n=s.length(); 6 Stack<Character> stack=new Stack<Character>(); 7 String result=""; 8 String temp=""; 9 for(int i=0;i<n;i++){ 10 char str=s.charAt(i); 11 if(str!=']'){ 12 stack.push(str); 13 }else{ 14 char ch=stack.pop(); 15 while(ch!='['){ 16 temp=ch+temp; 17 ch=stack.pop(); 18 } 19 String times=""; 20 while(!stack.isEmpty()){ 21 ch=stack.pop(); 22 if(Character.isDigit(ch)){ 23 times=ch+times; 24 }else{ 25 stack.push(ch); 26 break; 27 } 28 } 29 for(int j=0;j<Integer.parseInt(times);j++){ 30 for(int k=0;k<temp.length();k++){ 31 stack.push(temp.charAt(k)); 32 } 33 } 34 temp=""; 35 } 36 } 37 while(!stack.isEmpty()){ 38 result=stack.pop()+result; 39 } 40 return result; 41 } 42 }