Skip to content

Commit 84f041e

Browse files
committed
add LeetCode 20. 有效的括号
1 parent 6b7dbee commit 84f041e

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
2+
3+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
4+
>仰望星空的人,不应该被嘲笑
5+
6+
## 题目描述
7+
8+
9+
给定一个只包括` '(',')','{','}','[',']' `的字符串,判断字符串是否有效。
10+
11+
有效字符串需满足:
12+
13+
左括号必须用相同类型的右括号闭合。
14+
左括号必须以正确的顺序闭合。
15+
注意空字符串可被认为是有效字符串。
16+
17+
示例 1:
18+
19+
```javascript
20+
输入: "()"
21+
输出: true
22+
```
23+
24+
示例 2:
25+
26+
```javascript
27+
输入: "()[]{}"
28+
输出: true
29+
```
30+
31+
示例 3:
32+
33+
```javascript
34+
输入: "(]"
35+
输出: false
36+
```
37+
38+
示例 4:
39+
40+
```javascript
41+
输入: "([)]"
42+
输出: false
43+
```
44+
45+
示例 5:
46+
47+
```javascript
48+
输入: "{[]}"
49+
输出: true
50+
```
51+
52+
53+
## 题解
54+
55+
发现越靠后的左括号,最先匹配,也就是`后进先出`的思想,于是考虑使用栈这个数据结构。
56+
57+
```javascript
58+
/**
59+
* @param {string} s
60+
* @return {boolean}
61+
*/
62+
var isValid = function(s) {
63+
// 如果是奇数,不可能匹配成功,直接返回false
64+
if(s.length & 1) return false
65+
let stack = []
66+
for(let i=0;i<s.length;i++){
67+
if(s[i] === '(' || s[i] === '{' || s[i] === '[') stack.push(s[i])
68+
else if(s[i] === ')' && stack[stack.length-1] === '(') stack.pop()
69+
else if(s[i] === '}' && stack[stack.length-1] === '{') stack.pop()
70+
else if(s[i] === ']' && stack[stack.length-1] === '[') stack.pop()
71+
else return false
72+
}
73+
return !stack.length
74+
};
75+
```
76+
77+
78+
79+
## 最后
80+
文章产出不易,还望各位小伙伴们支持一波!
81+
82+
往期精选:
83+
84+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
85+
86+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
87+
88+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
89+
90+
```javascript
91+
学如逆水行舟,不进则退
92+
```

0 commit comments

Comments
 (0)