LeetCode.20_[栈]_有效的括号
程序员文章站
2024-01-28 17:14:46
...
1.题目
2.解题思路
检测到左括号,入栈
检测1到右括号,检查栈顶元素,匹配则出栈
3.代码实现
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++){
char item = s.charAt(i);
if(item == '(' || item == '[' || item == '{' ){
stack.push(item);
continue;
}
if(!stack.isEmpty()) {
if(item == ')' && stack.peek() == '(' )
stack.pop();
else if(item == ']' && stack.peek() == '[' )
stack.pop();
else if(item == '}' && stack.peek() == '{' )
stack.pop();
else
return false;
}else
stack.push(item);
}
if(stack.isEmpty()) return true;
else return false;
}
}