File tree 1 file changed +94
-0
lines changed
1 file changed +94
-0
lines changed Original file line number Diff line number Diff line change 31
31
i. 一个 integer 包含值 456
32
32
ii. 一个包含一个元素的嵌套列表
33
33
a. 一个 integer 包含值 789
34
+ ```
35
+
36
+ ## 解题
37
+
38
+ ### 深度优先遍历
39
+
40
+ ``` ts
41
+ /**
42
+ * 深度优先搜索
43
+ * @desc 时间复杂度 O(N) 空间复杂度 O(N)
44
+ * @param s
45
+ * @returns
46
+ */
47
+ export function deserialize(s : string ): NestedInteger {
48
+ let i = 0
49
+ return dfs (s )
50
+
51
+ function dfs(s : string ) {
52
+ if (s [i ] === ' [' ) {
53
+ i ++
54
+ const ni = new NestedInteger ()
55
+ while (s [i ] !== ' ]' ) {
56
+ ni .add (dfs (s ))
57
+ if (s [i ] === ' ,' ) i ++
58
+ }
59
+ i ++
60
+ return ni
61
+ }
62
+ else {
63
+ let negative = false
64
+ if (s [i ] === ' -' ) {
65
+ negative = true
66
+ i ++
67
+ }
68
+ let num = 0
69
+ while (i < s .length && isDigit (s [i ])) {
70
+ num = num * 10 + s [i ].charCodeAt (0 ) - ' 0' .charCodeAt (0 )
71
+ i ++
72
+ }
73
+ if (negative )
74
+ num = - num
75
+ return new NestedInteger (num )
76
+ }
77
+ }
78
+
79
+ function isDigit(ch : string ): boolean {
80
+ return ! isNaN (Number (ch ))
81
+ }
82
+ }
83
+ ```
84
+
85
+ ### 栈
86
+
87
+ ``` ts
88
+ /**
89
+ * 栈
90
+ * @desc 时间复杂度 O(N) 空间复杂度 O(N)
91
+ * @param s
92
+ * @returns
93
+ */
94
+ export function deserialize2(s : string ): NestedInteger {
95
+ if (s [0 ] !== ' [' ) return new NestedInteger (Number (s ))
96
+ const isDigit = (ch : string ): boolean => ! isNaN (Number (ch ))
97
+
98
+ const stack: NestedInteger [] = []
99
+ let num = 0
100
+ let negative = false
101
+ for (let i = 0 ; i < s .length ; i ++ ) {
102
+ const ch = s [i ]
103
+ if (ch === ' -' ) {
104
+ negative = true
105
+ }
106
+ else if (isDigit (ch )) {
107
+ num = num * 10 + ch .charCodeAt (0 ) - ' 0' .charCodeAt (0 )
108
+ }
109
+ else if (ch === ' [' ) {
110
+ stack .push (new NestedInteger ())
111
+ }
112
+ else if (ch === ' ,' || ch === ' ]' ) {
113
+ if (isDigit (s [i - 1 ])) {
114
+ if (negative ) num = - num
115
+ stack [stack .length - 1 ].add (new NestedInteger (num ))
116
+ }
117
+ num = 0
118
+ negative = false
119
+ if (ch === ' ]' && stack .length > 1 ) {
120
+ const ni = stack .pop ()!
121
+ stack [stack .length - 1 ].add (ni )
122
+ }
123
+ }
124
+ }
125
+
126
+ return stack .pop ()!
127
+ }
34
128
```
You can’t perform that action at this time.
0 commit comments