Skip to content

Commit f0caece

Browse files
committed
feat: add [20] 有效的括号
1 parent 4905834 commit f0caece

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

20.有效的括号.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* @lc app=leetcode.cn id=20 lang=typescript
3+
*
4+
* [20] 有效的括号
5+
*/
6+
7+
// @lc code=start
8+
function isValid(str: string): boolean {
9+
const leftMapping = {
10+
'(': ')',
11+
'{': '}',
12+
'[': ']',
13+
')': '(',
14+
'}': '{',
15+
']': '['
16+
}
17+
const stack: Array<string> = []
18+
for (let i = 0; i < str.length; i++) {
19+
const chars = str[i]
20+
if (['(', '{', '['].includes(chars)) {
21+
stack.push(chars)
22+
continue
23+
}
24+
if (stack[stack.length - 1] === leftMapping[chars]) {
25+
stack.pop()
26+
} else {
27+
return false
28+
}
29+
}
30+
31+
return stack.length === 0
32+
};
33+
// @lc code=end
34+

0 commit comments

Comments
 (0)