Skip to content

Commit b5195d6

Browse files
添加 20题 有效的括号 的解决方案
1 parent 977187e commit b5195d6

File tree

2 files changed

+81
-9
lines changed

2 files changed

+81
-9
lines changed

docs/Leetcode_Solutions/001._two_sum.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
所以返回 [0, 1]
1919
```
2020

21-
## 解决方案
21+
## 解题方案
2222

2323
> 思路 1
2424

docs/Leetcode_Solutions/020._valid_parentheses.md

Lines changed: 80 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,51 @@
1-
### 20. Valid Parentheses
1+
# 20. Valid Parentheses
22

3-
题目:
3+
**<font color=red>难度: Easy</font>**
44

5-
<https://leetcode.com/problems/valid-parentheses/>
65

6+
## 刷题内容
77

8-
难度:
8+
> 原题连接
99
10-
Easy
10+
* https://leetcode.com/problems/valid-parentheses
11+
* https://leetcode-cn.com/problems/valid-parentheses/description
1112

13+
> 内容描述
1214
13-
### 思路:
15+
```
16+
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
17+
18+
有效字符串需满足:
19+
20+
左括号必须用相同类型的右括号闭合。
21+
左括号必须以正确的顺序闭合。
22+
注意空字符串可被认为是有效字符串。
23+
24+
示例 1:
25+
26+
输入: "()"
27+
输出: true
28+
示例 2:
29+
30+
输入: "()[]{}"
31+
输出: true
32+
示例 3:
33+
34+
输入: "(]"
35+
输出: false
36+
示例 4:
37+
38+
输入: "([)]"
39+
输出: false
40+
示例 5:
41+
42+
输入: "{[]}"
43+
输出: true
44+
```
45+
46+
## 解题方案
47+
48+
> 思路 1
1449
1550
因为一共只有三种状况"(" -> ")", "[" -> "]", "{" -> "}".
1651

@@ -22,8 +57,6 @@ Easy
2257
- 出stack时是否对应
2358
- 最终stack是否为空
2459

25-
26-
2760
```python
2861
class Solution(object):
2962
def isValid(self, s):
@@ -50,3 +83,42 @@ class Solution(object):
5083
return stack == []
5184
```
5285

86+
> 思路 2
87+
88+
* 扩展性和可理解性强
89+
90+
```python
91+
class Solution:
92+
def isValid(self, s):
93+
"""
94+
:type s: str
95+
:rtype: bool
96+
"""
97+
if len(s) % 2 == 1:
98+
return False
99+
100+
index = 0
101+
stack = [i for i in s]
102+
map1 = {"(": ")", "[": "]", "{": "}"}
103+
104+
while len(stack) > 0:
105+
# 判断索引是否超过边界
106+
if index >= len(stack)-1:
107+
return False
108+
109+
b = stack[index]
110+
e = stack[index+1]
111+
112+
if b not in map1.keys():
113+
return False
114+
elif e in map1.keys():
115+
index += 1
116+
elif map1[b] == e:
117+
stack.pop(index+1)
118+
stack.pop(index)
119+
index = 0 if index-1<0 else index-1
120+
else:
121+
return False
122+
123+
return stack == []
124+
```

0 commit comments

Comments
 (0)