給定一個只包含 ()[]{} 的字符串,判斷括號是否有效。有效條件:左括號必須用相同類型的右括號閉合,且順序正確。
遍歷字符串,遇到左括號入棧,遇到右括號檢查棧頂是否匹配:
遍歷結束後,棧為空則完全匹配。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) return false;
char top = st.top();
if ((c == ')' && top == '(') ||
(c == '}' && top == '{') ||
(c == ']' && top == '[')) {
st.pop();
} else {
return false;
}
}
}
return st.empty();
}
};
"" -> true
"()" -> true
"()[]{}" -> true
"(]" -> false
"([)]" -> false
"{[]}" -> true
"(" -> false
")" -> false
若括號類型擴展到任意配對,可用哈希表 map<char,char> 存儲匹配關係,代碼更易維護:
unordered_map<char,char> mp = {{')','('}, {'}','{'}, {']','['}};
if (mp.count(c)) { // 右括號
if (st.empty() || st.top() != mp[c]) return false;
st.pop();
} else { // 左括號
st.push(c);
}