题目
给定一个字符串所表示的括号序列,包含以下字符: '(', ')'
, '{'
, '}'
, '['
and ']'
, 判定是否是有效的括号序列。
样例
括号必须依照 "()"
顺序表示, "()[]{}"
是有效的括号,但 "([)]"
则是无效的括号。
代码
用栈实现
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
// Write your code here
if(s==null || s.length()==0) return true;
Stack<Character> stack = new Stack<Character>();
//Stack<Character> s2 = new Stack<Character>();
for(int i=0; i<s.length(); i++){
char tmp = s.charAt(i);
if(stack.isEmpty()){
if(tmp==')' || tmp==']' || tmp=='}')
return false;
stack.add(tmp);
}else{
char peek = stack.peek();
if(tmp=='(' || tmp=='[' || tmp=='{'){
stack.add(tmp);
}else{
if(tmp==')' && peek!='(')
return false;
if(tmp==']' && peek!='[')
return false;
if(tmp=='}' && peek!='{')
return false;
stack.pop();
}
}
}
if(stack.isEmpty())
return true;
else
return false;
}
}