Skip to content

Commit 387c8ed

Browse files
committed
docs: replenish resolve
1 parent e7a52f3 commit 387c8ed

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

problemset/mini-parser/README.md

+94
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,98 @@
3131
i. 一个 integer 包含值 456
3232
ii. 一个包含一个元素的嵌套列表
3333
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+
}
34128
```

0 commit comments

Comments
 (0)