LeetCode-394. 字符串解码

题目链接

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. 将每个"[]"视为一层,字符串 res 用于记录当前层字符串
  2. String 类型的栈用于记录上面 n-1 层的每个字符串,Integer类型字符串记录当前层字符串应该重复的次数。
  3. 当遇到一个数字, 则将数字入栈。
  4. 当遇到一个 “[” 表示进入新的一层,则将** res 入栈,并将 res 置为 “”**, 表示新的一层的开始
  5. 当遇到一个 “]” 表示当前层的结束,必须返回上一层,则从栈中取出上一层的字符串str,并与当前层字符串 res 累加 count次。

Code:

class Solution {
    public String decodeString(String s) {
        String res = "";
        Stack<String> strstk = new Stack<>();
        Stack<Integer> coustk = new Stack<>();
        int len = s.length();
        for(int i = 0; i < len; i++) {
            char c= s.charAt(i);
            if(Character.isDigit(c)) {
                int count = 0;
                while (Character.isDigit(s.charAt(i))) {
                    count = count * 10 + s.charAt(i) - '0';
                    i++;
                }
                i--;
                coustk.push(count);
            } else if(c == '[') {   /* 进入到更内一层, 将外层 String 入栈, res = "", 用于记录当前层  */
                strstk.push(res);
                res = "";
            } else if(c == ']') {   /* 遇到 ']',将外层 String 取出, 并将当前层 res 累加 count次 */
                int count = coustk.pop();
                StringBuilder strsb = new StringBuilder(strstk.pop());
                while (count != 0) {
                    strsb.append(res);
                    count--;
                }
                res = strsb.toString();
            } else res += c;
        }
        return res;
    }
}

你可能感兴趣的:(算法)