给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
class Solution {
public boolean isValid(String s) {
Stack st = new Stack();//建立站对象存储符号
char[] ch = s.toCharArray();//把s变为有效的字符数组
int len = ch.length;
//假设长度为奇数,肯定无效
if((len & 1) != 0){
return false;
}
for(int i = 0; i < len; i++){
if(st.isEmpty()){//栈为空,直接入栈
st.push(ch[i]);
}else{//不为空则讨论栈顶元素是否与ch[i]配对。
if(isMatch(st.peek(),ch[i])){//是否配对
st.pop();//栈顶元素出栈
}else{
st.push(ch[i]);//不配对入栈
}
}
}
return st.isEmpty();
}
//a为栈顶元素,b为字符串最前元素
public static boolean isMatch(char a, char b){
switch(a){
case '(': if(b == ')') return true; else return false;
case '{': if(b == '}') return true; else return false;
case '[': if(b == ']') return true; else return false;
default : return false;
}
}
}