题目描述
给定一个只包括 '('、')'、'{'、'}'、'['、']' 的字符串 s,判断字符串是否有效。
有效字符串需满足:
-
左括号必须用相同类型的右括号闭合。
-
左括号必须以正确的顺序闭合。
-
每个右括号都有一个对应的相同类型的左括号。
输入描述
输入一行字符串 s。
输出描述
如果字符串有效,输出 true,否则输出 false。
示例 1
输入
text
()[]{}
输出
text
true
示例 2
输入
text
(]
输出
text
false
示例 3
输入
text
([)]
输出
text
false
C++ 解法
cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
stack<char> st;
unordered_map<char, char> mp = {
{')', '('},
{']', '['},
{'}', '{'}
};
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
if (st.empty()) {
cout << "false" << endl;
return 0;
}
if (st.top() != mp[c]) {
cout << "false" << endl;
return 0;
}
st.pop();
}
}
cout << (st.empty() ? "true" : "false") << endl;
return 0;
}