題目: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.
思路:
- 首先想到的便是使用棧的進(jìn)出棧來(lái)匹配,當(dāng)發(fā)現(xiàn)左括號(hào)時(shí)進(jìn)棧呀邢,右括號(hào)時(shí)進(jìn)行判斷;
- 如果棧頂元素為該右括號(hào)對(duì)應(yīng)的左括號(hào),則該元素出棧,否則返回不匹配;
- 如果進(jìn)出棧都無(wú)誤怎栽,則在程序結(jié)束后檢查棧中是否還有元素胞枕,無(wú)元素則返回匹配,有元素則返回不匹配.
代碼:
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 '[':
// 左括號(hào)進(jìn)棧
stack.push(ch);
break;
case ')':
// 右括號(hào) 棧為空 返回false
if (stack.empty()) {
return false;
// 右括號(hào) 棧頂元素不是對(duì)應(yīng)左括號(hào)返回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;
}
}
// 字符串遍歷結(jié)束后棧為空則代表所有括號(hào)匹配成功
return stack.empty();
}