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.
這道題用到了棧,遍歷字符串,將所有左括號壓入棧中,這裏有個重要的點,那就是右括號總是與離他最近的左括號配對,
所以接下來找到右括號之後,直接查詢棧頂,如果配對則推出,不配對則不做操作,最後判斷棧是否爲空,也就是全部配對
成功,來判斷最終結果。
代碼:
public class Solution {
public boolean isValid(String s) {
boolean result = true;
if(s.length() % 2 != 0){
return false;
}
Stack a = new Stack();
char[] b = s.toCharArray();
for(int i = 0; i < s.length();i++){//全部壓入棧中
if(b[i] == '(' || b[i] == '{' || b[i] == '['){
a.push(b[i]);
}
if(b[i] == ')' || b[i] == '}' || b[i] == ']' ){
if(a.empty()){
result = false;
}else{
if(((char)a.peek() + 1 == b[i]) || ((char)a.peek() + 2 == b[i])){
a.pop();
}
}
}
}
if(a.empty()){
result = true;
}else{
result = false;
}
return result;
}
}