[LeetCode] 394. Decode String_Medium tag: stack 666
2018-07-19 04:42 Johnson_强生仔仔 阅读(182) 评论(0) 编辑 收藏 举报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了!!!
(2018/07/20)update:
这里注意一定要append[", 1"], 而不是tuple!!!! 因为tuple是不能被change的!
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)])
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]
Code: 用stack,
1. init with "", stack = [""]
2. two helper functions, one get the num, one get the string
3. 如果 '[' , append
4. 如果 ']', 得到finalString, 然后再根据stack[-1] 是否为'['来看是否需要append或者stack[-1] +
5. 如果是digit, 得到digit string, 然后stack.append(int(digitString))
6. 如果是string,再根据stack[-1] 是否为'['来看是否需要append或者stack[-1] +
class Solution: def decodeString(self, s: str) -> str: n = len(s) i = 0 stack = [""] while i < n: if s[i] == '[': stack.append(s[i]) i += 1 elif s[i] == ']': curString = stack.pop() stack.pop() num = stack.pop() finalString = num * curString if stack[-1] == '[': stack.append(finalString) else: stack[-1] += finalString i += 1 elif s[i].isdigit(): endIndex = self.getNum(s, i) stack.append(int(s[i:endIndex])) i = endIndex elif s[i].isalpha(): endIndex = self.getStr(s, i) if stack[-1] == '[': stack.append(s[i:endIndex]) else: stack[-1] += s[i:endIndex] i = endIndex return stack[0] def getNum(self, s, start): while start < len(s) and s[start].isdigit(): start += 1 return start def getStr(self, s, start): while start < len(s) and s[start].isalpha(): start += 1 return start
4. Test cases
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc".