zoukankan      html  css  js  c++  java
  • [LC] 394. Decode String

    Given an encoded string, return its 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".

    Solution 1: Use 2 stacks
    class Solution:
        def decodeString(self, s: str) -> str:
            char_stack = []
            num_stack = []
            res, num, index = '', 0, 0
            while index < len(s):
                char = s[index]
                if char.isdigit():
                    num = 0
                    while index < len(s) and s[index].isdigit():
                        num = 10 * num + int(s[index])
                        index += 1
                    num_stack.append(num)
                elif char == '[':
                    char_stack.append(res)
                    res = ''
                    index += 1
                elif char == ']':
                    cur_char_lst = list(char_stack.pop())      
                    times = num_stack.pop()
                    for _ in range(times):
                        cur_char_lst.append(res)
                    res = ''.join(cur_char_lst)
                    index += 1
                else:
                    res += char
                    index += 1
            return res

    solution 2: Use 1 stack

    class Solution:
        def decodeString(self, s: str) -> str:
            stack = []
            cur_string, cur_num = '', 0
            for c in s:
                if c.isdigit():
                    cur_num = 10 * cur_num + int(c)
                elif c == '[':
                    stack.append(cur_string)
                    stack.append(cur_num)
                    cur_string = ''
                    cur_num = 0
                elif c == ']':
                    prev_num = stack.pop()
                    prev_string = stack.pop()
                    cur_string = prev_string + prev_num * cur_string
                else:
                    cur_string += c
            return cur_string
    class Solution {
        public String decodeString(String s) {
            char[] charArr = s.toCharArray();
            LinkedList<Object> stack = new LinkedList<>();
            int num = 0;
            for (char ch: charArr) {
                if (Character.isDigit(ch)) {
                    num = 10 * num + (ch - '0');
                } else if (ch == '[') {
                    stack.offerFirst(num);
                    num = 0;
                } else if (ch == ']') {
                    String cur = popBack(stack);
                    Integer preNum = (Integer)stack.pop();
                    for (int i = 0; i < preNum; i++) {
                        stack.offerFirst(cur);
                    }
                } else {
                    stack.offerFirst(String.valueOf(ch));
                }
            }
            return popBack(stack);
        }
        
        private String popBack(LinkedList<Object> stack) {
            LinkedList<String> buffer = new LinkedList<>();
            while (!stack.isEmpty() && (stack.peekFirst() instanceof String)) { 
                buffer.offerFirst((String)stack.pollFirst());
            }
            StringBuilder sb = new StringBuilder();
            while (!buffer.isEmpty()) {
                sb.append(buffer.pollFirst());
            }    
            return sb.toString();     
        }
    }
  • 相关阅读:
    链表面试题Java实现【重要】
    数据结构Java实现05----栈:顺序栈和链式堆栈
    数据结构Java实现06----中缀表达式转换为后缀表达式
    数据结构Java实现07----队列:顺序队列&顺序循环队列、链式队列、顺序优先队列
    栈和队列的面试题Java实现,Stack类继承于Vector这两个类都不推荐使用
    MySQL多表查询之外键、表连接、子查询、索引
    MySQL字符串函数、日期时间函数
    sqlplus登录、连接命令
    LeetCode 68 Text Justification
    cocos2d触摸事件处理机制(2.x和3.x变化)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11797621.html
Copyright © 2011-2022 走看看