有趣的括号c++代码
时间: 2023-11-04 09:15:20 浏览: 52
以下是一个使用 C++ 编写的有趣的括号代码,它可以判断一组括号序列是否合法(即左右括号匹配):
```c++
#include<iostream>
#include<stack>
#include<unordered_map>
using namespace std;
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> mapping = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
if (st.empty() || st.top() != mapping[c]) {
return false;
}
st.pop();
}
}
return st.empty();
}
// 测试代码
int main() {
cout << boolalpha << isValid("()") << endl; // true
cout << boolalpha << isValid("()[]{}") << endl; // true
cout << boolalpha << isValid("(]") << endl; // false
cout << boolalpha << isValid("([)]") << endl; // false
cout << boolalpha << isValid("{[]}") << endl; // true
return 0;
}
```
这个代码使用了栈来实现括号的匹配,具体实现思路与 Python 版本的代码类似。
这个代码的时间复杂度是 $O(n)$,其中 $n$ 是字符串的长度。