思路:每次添加新的字符时,判断当前字符与栈顶字符是否匹配(匹配原则 ()两个字符ASCII相差1,{} [] 两个字符ASCII相差2)
匹配则弹出栈顶,不匹配把当前的字符压入,最后判断栈空不空,空就匹配上了
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
int num = s.length();
for(int i = 0; i < num ;i ++)
{
if(!st.isEmpty() && (st.peek() == s.charAt(i) - 1 ||st.peek() == s.charAt(i) - 2))
{
st.pop();
}else{
st.push(s.charAt(i));
}
}
return st.isEmpty();
}
}