問題:數組
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.spa
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.code
解決:input
①一個個檢查給定的字符,若是是左括號都入棧;若是是右括號,檢查棧若是爲空,證實不能匹配,若是棧不空,彈出top,與當前掃描的括號檢查是否匹配。所有字符都檢查完了之後,判斷棧是否爲空,空則正確都匹配,不空則證實有沒匹配的。string
注意:it
檢查字符是用==,檢查String是用.isEqual(),由於String是引用類型,值相等可是地址可能不等。io
public class Solution {//13ms
public boolean isValid(String s) {
if(s.length() <= 1) return false;
Stack<Character> tmp = new Stack<>();//用於存儲左括號
for (int i = 0;i < s.length() ;i ++ ) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
tmp.push(s.charAt(i));
}else{
if(tmp.size() == 0) return false;
char top = tmp.pop();
if(s.charAt(i) == ')')
if(top != '(') return false;
if(s.charAt(i) == ']')
if(top != '[') return false;
if(s.charAt(i) == '}')
if(top != '{') return false;
}
}
return tmp.size() == 0;
}
}class
進階版:在遍歷到左括號時,將右括號入棧,這樣,只須要比較棧中的右括號與便利到的右括號是否相等便可。效率
public class Solution {//10ms
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(')
stack.push(')');
else if (c == '[')
stack.push(']');
else if (c == '{')
stack.push('}');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}進階
② 使用數組編寫棧結構,效率更高一些。
public class Solution {//7 ms
public boolean isValid(String s) {
if (s.isEmpty()) return true;
char[] schar = s.toCharArray();
char[] stack = new char[schar.length + 1];
stack[0] = '-';//爲防止數組下標越界
int p = 1;
for (int i = 0; i < schar.length; i ++) {
char c = schar[i];
switch(c) {
case '(':
stack[p ++] = ')';
break;
case '[':
stack[p ++] = ']';
break;
case '{':
stack[p ++] = '}';
break;
default://若case語句都不匹配,則執行該語句
if (stack[-- p] != c) return false;
}
}
return p == 1;
}
}
使用if-else
public class Solution { public boolean isValid(String s) { char[] stack = new char[s.length()]; int p = 0; if(s.length() % 2 != 0) return false; for (int i = 0;i < s.length() ;i ++ ) { if('(' == s.charAt(i)) stack[p ++] = ')'; else if('[' == s.charAt(i)) stack[p ++] = ']'; else if('{' == s.charAt(i)) stack[p ++] = '}'; else{ if(p > 0 && s.charAt(i) == stack[-- p]) continue; else{ return false; } } } return p == 0; } }