mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加0020.有效的括号 Java版本
This commit is contained in:
@ -138,7 +138,31 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
|
||||
```Java
|
||||
class Solution {
|
||||
public boolean isValid(String s) {
|
||||
Deque<Character> deque = new LinkedList<>();
|
||||
char ch;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
ch = s.charAt(i);
|
||||
//碰到左括号,就把相应的右括号入栈
|
||||
if (ch == '(') {
|
||||
deque.push(')');
|
||||
}else if (ch == '{') {
|
||||
deque.push('}');
|
||||
}else if (ch == '[') {
|
||||
deque.push(']');
|
||||
} else if (deque.isEmpty() || deque.peek() != ch) {
|
||||
return false;
|
||||
}else {//如果是右括号判断是否和栈顶元素匹配
|
||||
deque.pop();
|
||||
}
|
||||
}
|
||||
//最后判断栈中元素是否匹配
|
||||
return deque.isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
```python3
|
||||
|
Reference in New Issue
Block a user