Skip to content

Commit 20bb4de

Browse files
authored
Merge pull request MisterBooo#107 from ztianming/patch-2
Update LeetCode第20号问题:有效的括号.md
2 parents 175bbe4 + 50eaab9 commit 20bb4de

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

notes/LeetCode第20号问题:有效的括号.md

+49-3
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@
7171

7272
### 代码实现
7373

74-
```
74+
#### C++
75+
```c++
7576
class Solution {
7677
public:
7778
bool isValid(string s) {
@@ -109,7 +110,52 @@ public:
109110
}
110111
};
111112
```
113+
#### Java
114+
```java
115+
class Solution {
116+
public boolean isValid(String s) {
117+
//String open="({[";
118+
//String close="]})";
119+
120+
Stack<Character> stack = new Stack<Character>();
121+
122+
if(s.length() % 2 != 0)
123+
return false;
124+
125+
126+
for (char c : s.toCharArray())
127+
{
128+
if (c == '(') stack.push(')');
129+
else if (c == '{') stack.push('}');
130+
else if (c == '[') stack.push(']');
131+
else if (stack.isEmpty() || stack.pop() != c) return false;
132+
}
133+
134+
return stack.isEmpty();
135+
}
136+
137+
}
138+
```
139+
#### Python
140+
```python
141+
class Solution(object):
142+
def isValid(self, s):
143+
open_list = ["[", "{", "("]
144+
close_list = ["]", "}", ")"]
145+
stack = []
146+
147+
for i in s:
148+
if i in open_list:
149+
stack.append(i)
150+
elif i in close_list:
151+
pos=close_list.index(i)
152+
if len(stack)>0 and (open_list[pos] == stack[len(stack)-1]):
153+
stack.pop()
154+
else:
155+
return False
156+
if len(stack) == 0:
157+
return True
158+
```
112159

113160

114-
115-
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/gkcza.png)
161+
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/gkcza.png)

0 commit comments

Comments
 (0)