[LeetCode] 394. Decode String_Medium tag: stack 666

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

这个题目用一个stack, 初始化为[["", 1]], 每次看到[, stack.append(["", num]), 看到], 将stack pop出来, 并且将st*k 加入到stack[-1][0], 最后返回stack[0][0], 太6666了!!!



1. Constraints
1) 假设都有效, 并且不会有2[4]
2) 可以为empty

2. Ideas
stack T: O(n) S: O(n)

3. Code
 1 class Solution:
 2     def decodeString(self, s):
 3         stack, num = [["", 1]], ""
 4         for ch in s:
 5             if ch.isdigit():
 6                 num += ch
 7             elif ch == '[':
 8                 stack.append(["", int(num)])
 9             elif ch == ']':
10                 st, k = stack.pop()
11                 stack[-1][0] += st*k
12             else:
13                 stack[-1][0] += ch
14         return stack[0][0]

4. Test cases

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9333732.html