import java.util.Stack;
public class TestDemo11 {
// 括号匹配问题
/*
* 1.需要遍历字符串将所有左括号值放入栈中
* 2.需要判断你遍历完单链表,目前栈中是否有元素,如果没有就代表全部都是右括号
* 3.将栈的栈顶来与剩余的右括号来进行一一的比较;直至遍历完所有的str元素
* 4.如果元素还没有遍历完但是栈空可推出右括号多,
* 或者栈没有空元素已经遍历完则可以推出左括号多。
*
*
* */
public static boolean isValid(String str) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[' || str.charAt(i) == '(' || str.charAt(i) == '{') {
stack.push(str.charAt(i));
} else {//代表没有左括号
if (stack.isEmpty()) {
return false;
}else{
char ch = stack.peek();
if ((ch=='(' &&str.charAt(i) == ')')||(ch=='['&&str.charAt(i) == ']')||
ch=='{'&&str.charAt(i)=='}'){
stack.pop();
}else {
//右括号多
return false;
}
}
}
}if (!stack.isEmpty()){
return false;
}return true;
}
public static void main(String[] args) {
boolean flg=isValid("{[()]}");
System.out.println(flg);
}
}