括号匹配问题
题目:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
个人思路:
总共四种情况:
要么 左括号多
要么 右括号多
要么 左右括号不匹配
要么 匹配
新建一个栈
遇到 左括号 入栈
遇到 右括号
看是栈否为空 空的话 右括号多
然后 和 栈顶元素 比较 看是否匹配
匹配 出栈 顶元素
不匹配 左右不匹配 return ;
for循环走完后 如果 栈 还是非空 则左括号多 return ;
全部走完后 return true ;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(ch=='('||ch=='{' ||ch=='['){
stack.push(ch);
}else{
if(stack.empty()){
System.out.println("右括号多");
return false;
}
char top = stack.peek();
if(ch==')'&&top=='(' || ch=='}'&&top=='{' ||ch==']'&&top=='['){
stack.pop();
}else{
System.out.println("左右括号不匹配");
return false;
}
}
}
if(!stack.empty()){
System.out.println("左括号多");
return false;
}
return true;
}
}