题目描述
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
'('
,
')'
,
'{'
,
'}'
,
'['
and
']'
的字符串是否合法.
解题思路
看到此类题立马应该想到使用栈。遇到右括号则应检查是否和栈顶元素匹配,遇到左括号应该入栈。
在解题过程中,使用了一点小技巧来避免过的来判定括号类型。我们定义:
Value(() = 0 ,Value()) = 5;
Value({) = 1,Value(}) = 4;
Value([) = 2,Value(]) = 3;
那么相匹配的两个括号的Value值的和必定为5.
另外:需要考虑到栈为空遇到右括号的情况。
代码
public boolean isValid(String s) {
if(s==null)
return true;
if(s.length()==0)
return true;
Stack<String> stack = new Stack<String>();
String ch = "";
int value;
for(int i = 0;i < s.length();i++){
ch = s.charAt(i)+"";
value = getBracketsValue(ch);
if(value >=3){
if(stack.size()==0){
return false;
} else {
if(getBracketsValue(stack.peek())+value==5){
stack.pop();
} else {
return false;
}
}
} else {
stack.push(ch);
}
}
if(stack.isEmpty()){
return true;
}
return false;
}
public int getBracketsValue(String s){
if(s.equals("(")){
return 0;
} else if(s.equals(")")){
return 5;
} else if(s.equals("{")){
return 1;
} else if(s.equals("}")){
return 4;
}else if(s.equals("[")){
return 2;
} else if(s.equals("]")){
return 3;
} else {
return -1;
}
}