394. Decode String 解码icc字符串3[i2[c]]

[抄题]:

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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

多层括号都没想到是stack,我去

[英文数据结构或算法,为什么不用别的数据结构或算法]:

两个stack可以分开处理字母和数组

[一句话思路]:

左括号就之前的不加了,右括号就开始append求和

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

开始append的时候,把intstack里的数取出来直接用,

不要赋值给k, 会导致k的改变。(k保存了之前的次数,还有用。)

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

左括号就之前的不加了,右括号就开始append求和

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

class Solution {
  public String decodeString(String s) {
    //ini: 2 stacks, 1 stringbuilder
    Stack<StringBuilder> strStack = new Stack<>();
    Stack<Integer> intStack = new Stack<>();
    StringBuilder cur = new StringBuilder();
    int k = 0;
    
    //cc
    if (s == null) return "";
    
    //for loop : 4 cases
    for (char c : s.toCharArray()) {
      if (Character.isDigit(c)) {
        k = k * 10 + c - '0';
      }else if (c == '[') {
        //stop add
        intStack.push(k);
        strStack.push(cur);
        k = 0;
        cur = new StringBuilder();
      }else if (c == ']') {
        //begin to append
        StringBuilder temp = cur;
        //k = intStack.pop();
        cur = strStack.pop();
        for (int i = intStack.pop(); i > 0; i--)
          cur.append(temp);
      }else cur.append(c);
    }
    
    return cur.toString();
  }
  
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9364499.html