# Heading
Tags: algorithms airbnb amazon bloomberg facebook google microsoft twitter zenefits string stack
Langs: c cpp csharp dart elixir erlang golang java javascript kotlin php python python3 racket ruby rust scala swift typescript
- algorithms
- Easy (43.90%)
- Likes: 4382
- Dislikes: -
- Total Accepted: 1.7M
- Total Submissions: 4M
- Testcase Example: '"()"'
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
示例 3:
输入:s = "(]" 输出:false
提示:
1 <= s.length <= 104
s
仅由括号'()[]{}'
组成
/*
* @lc app=leetcode.cn id=20 lang=javascript
*
* [20] 有效的括号
*/
// @lc code=start
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
if (s.length % 2 !== 0) {
return false
}
const stack = []
const map = {
'(': ')',
'[': ']',
'{': '}',
}
for (let char of s) {
if (['(', '{', '['].includes(char)) {
stack.push(char)
} else {
if (stack.length === 0) {
return false
}
if (char !== map[stack.pop()]) {
return false
}
}
}
return stack.length === 0
}
// @lc code=end
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
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