LeetCode(20)判斷字串合法括號
問題
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
解決,考慮使用棧的先進後出特性來存放這個字串。將字串中字元從頭開始入棧,如果棧空,則直接入棧。如果非空,則判斷棧頂字元。根據不同的情況,判斷是否與當前字元與棧頂字元是否構成一個完整的括號。如果是,則棧頂出棧,如果不是,則當前字元入棧。最後,返回棧是否非空,空,表明是合法括號字串;非空,則有多餘的字元不夠成合法括號字串。注意,對於引數的特性情況的判斷。
java解決
class Solution {
public boolean isValid(String s) {
// 引數合法性判斷
if(s == null){
return false;
}
int size = s.length();
if (size < 1 || s.equals("")) {
return true;
}
// 以連結串列作為棧
LinkedList<Character> stack = new LinkedList<Character>();
for (int i = 0; i < size; i++) {
char tmp = s.charAt(i);
if (stack.size() == 0) {
stack.push(tmp);
} else {
char top = stack.getFirst();
if (top == '(') {
if (tmp == ')') {
stack.pop();
} else {
stack.push(tmp);
}
} else if (top == '[') {
if (tmp == ']') {
stack.pop();
} else {
stack.push(tmp);
}
} else if (top == '{') {
if (tmp == '}') {
stack.pop();
} else {
stack.push(tmp);
}
} else {
return false;
}
}
}
return stack.isEmpty();
}
}