Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update LeetCode第20号问题:有效的括号.md #107

Merged
merged 1 commit into from
Jul 31, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update LeetCode第20号问题:有效的括号.md
添加Java、python版代码实现
  • Loading branch information
ztianming committed Jul 29, 2020
commit 50eaab9e9d2ba9ada5443f3e65d870c85097c486
52 changes: 49 additions & 3 deletions notes/LeetCode第20号问题:有效的括号.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@

### 代码实现

```
#### C++
```c++
class Solution {
public:
bool isValid(string s) {
Expand Down Expand Up @@ -109,7 +110,52 @@ public:
}
};
```
#### Java
```java
class Solution {
public boolean isValid(String s) {
//String open="({[";
//String close="]})";

Stack<Character> stack = new Stack<Character>();

if(s.length() % 2 != 0)
return false;


for (char c : s.toCharArray())
{
if (c == '(') stack.push(')');
else if (c == '{') stack.push('}');
else if (c == '[') stack.push(']');
else if (stack.isEmpty() || stack.pop() != c) return false;
}

return stack.isEmpty();
}

}
```
#### Python
```python
class Solution(object):
def isValid(self, s):
open_list = ["[", "{", "("]
close_list = ["]", "}", ")"]
stack = []

for i in s:
if i in open_list:
stack.append(i)
elif i in close_list:
pos=close_list.index(i)
if len(stack)>0 and (open_list[pos] == stack[len(stack)-1]):
stack.pop()
else:
return False
if len(stack) == 0:
return True
```



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