酷代码 AI
菜单
服务商

C++实现:判断由 6 种括号组成的字符串是否为合法括号序列

```cpp #include <iostream> #include <stack> #include <string> // 检查字符对是否匹配 bool isMatching(char open, char close) { if (open == '(' && close == ')') return true; if (open == '[' && close == ']') return true; if (open == '{' && close == '}') return true; return false; } // 检查字符串是否为合法括号序列 bool isValid(const std::string& s) { std::stack<char> st; for (char c : s) { if (c == '(' || c == '[' || c == '{') { st.push(c); } else { if (st.empty()) return false; char top = st.top(); st.pop(); if (!isMatching(top, c)) return false; } } return st.empty(); } int main() { int T; std::cin >> T; std::cin.ignore(); // 忽略换行符 for (int i = 0; i < T; ++i) { std::string s; std::getline(std::cin, s); if (isValid(s)) { std::cout << "YES" << std::endl; } else { std::cout << "NO" << std::endl; } } return 0; } ``` ######[AI问答 | 339点数解答 | 2025-12-03 18:22:21]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]