Skip to content

Commit 50579bd

Browse files
committed
20
1 parent ec38656 commit 50579bd

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@
2020
* [17. Letter Combinations of a Phone Number](leetCode-17-Letter-Combinations-of-a-Phone-Number.md)
2121
* [18. 4Sum](leetCode-18-4Sum.md)
2222
* [19. Remove Nth Node From End of List](leetCode-19-Remov-Nth-Node-From-End-of-List.md)
23+
* [20. Valid Parentheses](leetCode-20-Valid Parentheses.md)
2324
* [79. Word Search](leetCode-79-Word-Search.md)

leetCode-20-Valid Parentheses.md

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 题目描述(简单难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/20.png)
4+
5+
括号匹配问题。
6+
7+
如果只有一种括号,我们完全可以用一个计数器 count ,遍历整个字符串,遇到左括号加 1 ,遇到右括号减 1,遍历结束后,如果 count 等于 0 ,则表示全部匹配。但如果有多种括号,像 ( [ ) ] 这种情况它依旧会得到 0,所以我们需要用其他的方法。
8+
9+
栈!
10+
11+
遍历整个字符串,遇到左括号就入栈,然后遇到和栈顶对应的右括号就出栈,遍历结束后,如果栈为空,就表示全部匹配。
12+
13+
```java
14+
public boolean isValid(String s) {
15+
Stack<Character> brackets = new Stack<Character>();
16+
for(int i = 0;i < s.length();i++){
17+
char c = s.charAt(i);
18+
switch(c){
19+
case '(':
20+
case '[':
21+
case '{':
22+
brackets.push(c);
23+
break;
24+
case ')':
25+
if(!brackets.empty()){
26+
if(brackets.peek()== '('){
27+
brackets.pop();
28+
}else{
29+
return false;
30+
}
31+
}else{
32+
return false;
33+
}
34+
break;
35+
case ']':
36+
if(!brackets.empty()){
37+
if(brackets.peek()=='['){
38+
brackets.pop();
39+
}else{
40+
return false;
41+
}
42+
}else{
43+
return false;
44+
}
45+
break;
46+
case '}':
47+
if(!brackets.empty()){
48+
if(brackets.peek()=='{'){
49+
brackets.pop();
50+
}else{
51+
return false;
52+
}
53+
}else{
54+
return false;
55+
}
56+
57+
}
58+
}
59+
60+
return brackets.empty();
61+
}
62+
```
63+
64+
时间复杂度:O(n)。
65+
66+
空间复杂度:O(n)。
67+
68+
#
69+
70+
如果学过数据结构,一定写过计算器,括号匹配问题一定遇到过的。

0 commit comments

Comments
 (0)