題目:Given a string containing just the characters '(',')','{','}','[' and ']', determine if the input string a valid.
the brackets must close in the correct order.
如:'()' and "()[]{}" are all valid but "(]" and "([)]" are not.
思路:
- 首先想到的便是使用棧的進出棧來匹配,當發(fā)現(xiàn)左括號時進棧,右括號時進行判斷;
- 如果棧頂元素為該右括號對應的左括號,則該元素出棧,否則返回不匹配;
- 如果進出棧都無誤,則在程序結束后檢查棧中是否還有元素,無元素則返回匹配,有元素則返回不匹配.

匹配成功 - ()[]{}

匹配失敗 - ([)]
代碼:
private boolean match(String str) {
int length = str.length();
Stack stack = new Stack();
for (int index = 0; index < length; index++) {
char ch = str.charAt(index);
switch (ch) {
case '(':
case '{':
case '[':
// 左括號進棧
stack.push(ch);
break;
case ')':
// 右括號 棧為空 返回false
if (stack.empty()) {
return false;
// 右括號 棧頂元素不是對應左括號返回false
} else if ('(' != (char) stack.pop()) {
return false;
}
break;
case '}':
if (stack.empty()) {
return false;
} else if ('{' != (char) stack.pop()) {
return false;
}
break;
case ']':
if (stack.empty()) {
return false;
} else if ('[' != (char) stack.pop()) {
return false;
}
break;
default:
break;
}
}
// 字符串遍歷結束后棧為空則代表所有括號匹配成功
return stack.empty();
}