File tree Expand file tree Collapse file tree 2 files changed +81
-9
lines changed Expand file tree Collapse file tree 2 files changed +81
-9
lines changed Original file line number Diff line number Diff line change 18
18
所以返回 [0, 1]
19
19
```
20
20
21
- ## 解决方案
21
+ ## 解题方案
22
22
23
23
> 思路 1
24
24
Original file line number Diff line number Diff line change 1
- ### 20. Valid Parentheses
1
+ # 20. Valid Parentheses
2
2
3
- 题目:
3
+ ** < font color = red >难度: Easy</ font > **
4
4
5
- < https://leetcode.com/problems/valid-parentheses/ >
6
5
6
+ ## 刷题内容
7
7
8
- 难度:
8
+ > 原题连接
9
9
10
- Easy
10
+ * https://leetcode.com/problems/valid-parentheses
11
+ * https://leetcode-cn.com/problems/valid-parentheses/description
11
12
13
+ > 内容描述
12
14
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
14
49
15
50
因为一共只有三种状况"(" -> ")", "[ " -> "] ", "{" -> "}".
16
51
22
57
- 出stack时是否对应
23
58
- 最终stack是否为空
24
59
25
-
26
-
27
60
``` python
28
61
class Solution (object ):
29
62
def isValid (self , s ):
@@ -50,3 +83,42 @@ class Solution(object):
50
83
return stack == []
51
84
```
52
85
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
+ ```
You can’t perform that action at this time.
0 commit comments