package com.lt.datastructure.Array;
import java.util.Stack;
/**
* 括号的匹配
*
* 遍历字符串s,如果是左括号,入栈
* 如果当前字符是右括号,栈为空,则匹配失败
* 如果当前字符是右括号,栈不为空,将其与栈顶字符匹配,匹配不成功则返回false
* 遍历判断结束后,当且仅当栈为空,匹配成功
*/
public class Solution { public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
//case:左括号
if(c=='(' || c=='[' || c=='{'){
stack.push(c);
}
else{
//case:右括号
if(stack.isEmpty()) return false; char chartop = stack.pop();
if(c==')' && chartop !='(') return false;
if(c==']' && chartop !='[') return false;
if(c=='}'&& chartop!='{') return false;
}
}
return stack.isEmpty();
}
//测试用例
public static void main(String[] args) {
System.out.println(new Solution().isValid("(){}"));
}
}