提交 8473c84f 编写于 作者: L Lu Zhao 提交者: labuladong

add 20 java

上级 4d4a55f2
......@@ -112,4 +112,28 @@ char leftOf(char c) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
```java
//基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈
//如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。
//最后,我们还需要检查堆栈是否为空
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for(char c : s.toCharArray()){
//是左括号就将相对应的右括号入栈
if(c=='(') {
stack.offerLast(')');
}else if(c=='{'){
stack.offerLast('}');
}else if(c=='['){
stack.offerLast(']');
}else if(stack.isEmpty() || stack.pollLast()!=c){//出现右括号,检查堆栈是否为空,以及顶部元素是否与该右括号相同
return false;
}
}
return stack.isEmpty();
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册