Skip to content

Commit

Permalink
add 20 java
Browse files Browse the repository at this point in the history
  • Loading branch information
lzhao819 authored and labuladong committed Nov 12, 2020
1 parent 4d4a55f commit 8473c84
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion 高频面试系列/合法括号判定.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,28 @@ char leftOf(char c) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>

======其他语言代码======
======其他语言代码======

```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();
}

```

0 comments on commit 8473c84

Please sign in to comment.