-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path394.Decode-String.py
102 lines (77 loc) · 2.21 KB
/
394.Decode-String.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# https://leetcode.com/problems/decode-string/
#
# algorithms
# Medium (45.84%)
# Total Accepted: 118,973
# Total Submissions: 259,545
from collections import deque
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
if length < 2:
return s
stack, i = deque(), 0
while i < length:
if s[i] == ']':
last_s = stack[-1]
string = ''
while type(last_s) is not int:
string = last_s + string
stack.pop()
last_s = stack[-1]
stack.pop()
stack.append(last_s * string)
i += 1
elif s[i].isdigit():
j = i + 1
while s[j].isdigit():
j += 1
stack.append(int(s[i:j]))
i = j + 1
elif s[i].isalpha():
j = i + 1
while j < length and s[j].isalpha():
j += 1
stack.append(s[i:j])
i = j
res = []
while stack:
res.insert(0, stack.pop())
return ''.join(res)
from collections import deque
class Solution1(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = deque()
length = len(s)
i = 0
while i < length:
if s[i].isalpha():
j = i + 1
while j < length and s[j].isalpha():
j += 1
stack.append(s[i:j])
i = j
elif s[i].isdigit():
j = i + 1
while j < length and s[j].isdigit():
j += 1
stack.append(int(s[i:j]))
i = j + 1
elif s[i] == ']':
tmp = ''
while stack and type(stack[-1]) is not int:
tmp = stack[-1] + tmp
stack.pop()
n = stack.pop()
tmp = n * tmp
stack.append(tmp)
i += 1
return ''.join(stack)