forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
35 lines (30 loc) · 783 Bytes
/
index.ts
File metadata and controls
35 lines (30 loc) · 783 Bytes
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
export function isValidParentheses(str: string): boolean {
const arr = str.split('')
const len = arr.length
if (isOdd(len)) return false
let i = 0
let stack = []
while (i < len) {
if (isPair(stack[stack.length - 1], arr[i])) {
stack.pop()
} else {
if (isClosingParentheses(arr[i])) return false
stack.push(arr[i])
}
i++
}
return !stack.length
}
function isPair(x: string, y: string): boolean {
if (x === '(' && y === ')') return true
if (x === '{' && y === '}') return true
if (x === '[' && y === ']') return true
return false
}
function isOdd(num: number): boolean {
return !(num % 2 === 0)
}
function isClosingParentheses(x: string): boolean {
if (x === ')' || x === '}' || x === ']') return true
return false
}