Skip to content

Commit 8473c84

Browse files
lzhao819labuladong
authored andcommitted
add 20 java
1 parent 4d4a55f commit 8473c84

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

高频面试系列/合法括号判定.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,28 @@ char leftOf(char c) {
112112
<img src="../pictures/qrcode.jpg" width=200 >
113113
</p>
114114

115-
======其他语言代码======
115+
======其他语言代码======
116+
117+
```java
118+
//基本思想:每次遇到左括号时都将相对应的右括号')',']'或'}'推入堆栈
119+
//如果在字符串中出现右括号,则需要检查堆栈是否为空,以及顶部元素是否与该右括号相同。如果不是,则该字符串无效。
120+
//最后,我们还需要检查堆栈是否为空
121+
public boolean isValid(String s) {
122+
Deque<Character> stack = new ArrayDeque<>();
123+
for(char c : s.toCharArray()){
124+
//是左括号就将相对应的右括号入栈
125+
if(c=='(') {
126+
stack.offerLast(')');
127+
}else if(c=='{'){
128+
stack.offerLast('}');
129+
}else if(c=='['){
130+
stack.offerLast(']');
131+
}else if(stack.isEmpty() || stack.pollLast()!=c){//出现右括号,检查堆栈是否为空,以及顶部元素是否与该右括号相同
132+
return false;
133+
}
134+
}
135+
return stack.isEmpty();
136+
}
137+
138+
```
139+

0 commit comments

Comments
 (0)