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".

求解

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

 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 }
原文地址:https://www.cnblogs.com/kexinxin/p/10235379.html