File tree 2 files changed +111
-0
lines changed
solution/0394.Decode String
2 files changed +111
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 字符串解码
2
+
3
+ ### 问题描述
4
+
5
+ 给定一个经过编码的字符串,返回它解码后的字符串。
6
+
7
+ 编码规则为: ` k[encoded_string] ` ,表示其中方括号内部的 ` encoded_string ` 正好重复 ` k `
8
+ 次。注意 ` k ` 保证为正整数。
9
+
10
+ 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要
11
+ 求的。
12
+
13
+ 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 ` k ` ,例如不会出现像
14
+ ` 3a ` 或 ` 2[4] ` 的输入。
15
+
16
+ ** 示例:**
17
+ ```
18
+ s = "3[a]2[bc]", 返回 "aaabcbc".
19
+ s = "3[a2[c]]", 返回 "accaccacc".
20
+ s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
21
+ ```
22
+
23
+
24
+ ### 解法
25
+
26
+ 递归求解。设所求为` ans ` 。遍历字符串,每次遇到字母,则加入` ans ` ;每次遇到数字,则存下;
27
+ 遇到` [ ` ,则找到与其匹配的` ] ` ,并个位置之间的进行递归求解,并将所得结果乘以遇到的数字,
28
+ 再加入` ans ` 。
29
+
30
+ ``` python
31
+ class Solution (object ):
32
+ def decodeString (self , s ):
33
+ def deco (s ):
34
+ if ' [' not in s and ' ]' not in s:
35
+ return s
36
+ i = j = 0
37
+ ans = ' '
38
+ count = ' '
39
+ while i < len (s):
40
+ if s[i].isdigit():
41
+ count += s[i]
42
+ i += 1
43
+ elif s[i].isalpha():
44
+ ans += s[i]
45
+ i += 1
46
+ elif s[i] == ' [' :
47
+ j = i + 1
48
+ zuo = 0
49
+ while j < len (s):
50
+ if s[j] == ' [' :
51
+ zuo += 1
52
+ j += 1
53
+ elif s[j] == ' ]' :
54
+ if zuo != 0 :
55
+ zuo -= 1
56
+ j += 1
57
+ else :
58
+ if not count:
59
+ ans += deco(s[i + 1 :j])
60
+ else :
61
+ ans += int (count) * deco(s[i + 1 :j])
62
+ count = ' '
63
+ i = j + 1
64
+ break
65
+ else :
66
+ j += 1
67
+ return ans
68
+ return deco(s)
69
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def decodeString (self , s ):
3
+ """
4
+ :type s: str
5
+ :rtype: str
6
+ """
7
+ def deco (s ):
8
+ if '[' not in s and ']' not in s :
9
+ return s
10
+ i = j = 0
11
+ ans = ''
12
+ count = ''
13
+ while i < len (s ):
14
+ if s [i ].isdigit ():
15
+ count += s [i ]
16
+ i += 1
17
+ elif s [i ].isalpha ():
18
+ ans += s [i ]
19
+ i += 1
20
+ elif s [i ] == '[' :
21
+ j = i + 1
22
+ zuo = 0
23
+ while j < len (s ):
24
+ if s [j ] == '[' :
25
+ zuo += 1
26
+ j += 1
27
+ elif s [j ] == ']' :
28
+ if zuo != 0 :
29
+ zuo -= 1
30
+ j += 1
31
+ else :
32
+ if not count :
33
+ ans += deco (s [i + 1 :j ])
34
+ else :
35
+ ans += int (count ) * deco (s [i + 1 :j ])
36
+ count = ''
37
+ i = j + 1
38
+ break
39
+ else :
40
+ j += 1
41
+ return ans
42
+ return deco (s )
You can’t perform that action at this time.
0 commit comments