-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkValidString.ts
41 lines (35 loc) · 1.13 KB
/
checkValidString.ts
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
// <Stack>
// Time: O(n)
// Space: O(n)
function checkValidString(s: string): boolean {
const n = s.length
const parenthesesStack: number[] = []
const asteriskStack: number[] = []
// 1. traverse the string
for (let i = 0; i < n; ++i) {
const char = s[i]
if (char === '(') {
parenthesesStack.push(i)
} else if (char === '*') {
asteriskStack.push(i)
} else if (parenthesesStack.length) {
parenthesesStack.pop()
} else if (asteriskStack.length) {
asteriskStack.pop()
} else {
return false
}
}
// 2. handle the rest elements in the two stacks
while (parenthesesStack.length && asteriskStack.length) {
const parenthesisIndex = parenthesesStack.pop()!
const asteriskIndex = asteriskStack.pop()!
// 3. the index of the asterisk can not be less than that of the left parenthesis
if (parenthesisIndex > asteriskIndex) {
return false
}
}
// 4. all the left parenthesis should be paired
return parenthesesStack.length === 0
}
export { checkValidString }