問題:
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.
括號必須以正確的順序關閉,“()”和“()[] {}”全部有效,但“(]”和“([)]”不是。
思路:
依次讀取字符串,用棧存入括號的前半部分,也就是:'(','[','{'。若遇到括號的後半部分,檢查棧頂的括號是否與此時的括號相匹配,若匹配則讓棧頂元素出棧,再進行匹配下一組,直到棧爲空。一旦遇到不匹配的情況,就返回False.
代碼:
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '[' || ch == '{'){
stack.push(ch);
}
if(ch == ')' && (stack.isEmpty() || stack.pop()!='(')){
return false;
}
if(ch == ']' && (stack.isEmpty() || stack.pop()!='[')){
return false;
}
if(ch == '}' && (stack.isEmpty() || stack.pop()!='{')){
return false;
}
}
if(!stack.empty()){
return false;
}
return true;
}