酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

输入一个由括号'(',')','{','}','[',']'组成的字符串,判断字符串是否合法,写程序完成此转换,要求使用class类。部分代码已给出,请将代码填补完整。合法是指括号按顺序结束,如‘()’和‘([])’是有效的,而’{]’和’([)]’不是合法的。 #include <iostream> using namespace std; class Solution { public: bool isValid(string s) { /*在此补全代码*/ } }; int main(){ Solution s; string str; getline(cin, str); bool res = s.isValid(str); cout<<res; return 0; } 编程要求 根据提示,在右侧编辑器补充代码。 测试说明 输入描述: 输入一个字符串,全部由‘(’,’)’,’{’,’}’,‘[’,’]’组成 输出描述: 如果合法输出1,否则输出0 语言方向:C++

```cpp #include <iostream> #include <stack> 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(); st.pop(); if ((c == ')' && top!= '(') || (c == ']' && top!= '[') || (c == '}' && top!= '{')) { return false; } } } return st.empty(); } }; int main(){ Solution s; string str; getline(cin, str); bool res = s.isValid(str); cout<<res; return 0; } ``` 额外需要注意的逻辑点: 1. 注意边界情况,比如输入为空字符串时的处理。 2. 对于栈的操作要确保没有越界。 3. 考虑不同括号组合的各种可能情况,确保代码的正确性和完整性。 [2025-03-07 12:50:41 | AI写代码神器 | 278点数解答]

相关提问