給定一個只包含 '('、')'、'{'、'}'、'['、']' 的字符串,判斷括號是否有效。有效條件:左括號必須用相同類型的右括號閉合,且閉合順序正確。
"()"、"()[]{}" → true"(]"、"([)]" → false(、{、[ 入棧| 右括號 | 對應左括號 |
|---|---|
| ) | ( |
| ] | [ |
| } | { |
#include <stack>
#include <string>
using namespace std;
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 != '{')) return false;
st.pop();
}
}
return st.empty();
}
};