Skip to content

Commit e65160b

Browse files
authored
Update 394._decode_string.md
1 parent 6132c6d commit e65160b

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

docs/Leetcode_Solutions/Python/394._decode_string.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
3333

3434
就很像一个basic calculator,224题
3535

36+
iterative, 栈
37+
3638
beats 100%
3739

3840
```python
@@ -59,3 +61,77 @@ class Solution:
5961
stack[-1][0] += prev_str * cnt
6062
return stack[0][0]
6163
```
64+
65+
66+
67+
> 思路 2
68+
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******
69+
70+
递归
71+
72+
beats 100%
73+
74+
```python
75+
class Solution:
76+
def decodeString(self, s):
77+
"""
78+
:type s: str
79+
:rtype: str
80+
"""
81+
if not s or len(s) == 0:
82+
return ''
83+
84+
def helper(s):
85+
res = ''
86+
open_idx = s.find('[')
87+
if open_idx != -1:
88+
open_cnt = 1
89+
idx = open_idx + 1
90+
while idx < len(s) and open_cnt > 0: # 找到与第一个 '[' 匹配的 ']'
91+
if s[idx] == '[':
92+
open_cnt += 1
93+
elif s[idx] == ']':
94+
open_cnt -= 1
95+
idx += 1
96+
close_idx = idx - 1
97+
tmp_str = ''
98+
cnt, i = 0, 0
99+
while i < open_idx and not s[i].isdigit(): # 找到数字前可能有的字符串,见test case2
100+
tmp_str += s[i]
101+
i += 1
102+
cnt = int(s[i:open_idx])
103+
return tmp_str + cnt * helper(s[open_idx+1:close_idx]) + helper(s[close_idx+1:])
104+
else:
105+
return s
106+
107+
return helper(s)
108+
```
109+
110+
111+
112+
113+
114+
115+
116+
117+
118+
119+
120+
121+
122+
123+
124+
125+
126+
127+
128+
129+
130+
131+
132+
133+
134+
135+
136+
137+

0 commit comments

Comments
 (0)