原題目
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.
翻譯
給一個僅包含’(’, ‘)’, ‘{’, ‘}’, ‘[’ 和 ']'的字符串,然後判斷這個字符串是否是有效的。
括號必須按照順序進行閉合,比如"()" 和 “()[]{}” 都是有效的,但是 “(]” 和 “([)]” 不是有效的.
解題思路
這是一個典型的棧應用的例子。如果是字符’(’,’[’, ‘{’, 將其壓入棧,如果是’)’,’]’,’}’
就從棧中取頂部字符,如果棧爲空或者不相匹配,那麼就可以認定是無效的。
如果和棧頂元素匹配,就繼續遍歷字符串判定。
時間複雜度:O(n)
空間複雜度:O(2)
代碼示例
public static boolean isValid(String s) {
if (s == null ||s.length() <= 1){
return false;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i <= s.length()-1;i++){
Character ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{'){
stack.push(ch);
}else{
if (stack.size() == 0){
return false;
}
Character sch = stack.pop();
if (ch == ')'){
if (sch != '('){
return false;
}
}else if (ch == ']'){
if (sch != '['){
return false;
}
}else if (ch == '}'){
if (sch != '{'){
return false;
}
}
}
}
return stack.size() == 0;
}