题目
解答:
’(‘,’[‘,'{':进栈
')',']','}’:出栈,栈为空,返回false
最后,栈为空,返回true。栈不为空,说明有左大小中括号没被匹配上,反回false
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
if(s == null)
return false;
int len = s.length();
Stack<Character> st = new Stack<>();
int i =0;
while(i<len ){
if(isValid(s.charAt(i))){
switch(s.charAt(i)){
case '(':
case '[':
case '{':
st.push(s.charAt(i));
i++;
break;
case ')':
if(!st.empty()){
if(st.peek() == '('){
st.pop();
i++;
break;
}else
return false;
}else
return false;
case ']':
if(!st.empty()){
if(st.peek() == '['){
st.pop();
i++;
break;
}else
return false;
}else
return false;
case '}':
if(!st.empty()){
if(st.peek() == '{'){
st.pop();
i++;
break;
}else
return false;
}else
return false;
}
}else
i++;
}
if(st.isEmpty())
return true;
else
return false;
}
public boolean isValid(char a){
if(a == '('||a == ')'||a == '['||a == ']'||a == '{'||a == '}')
return true;
else
return false;
}
}