2 条题解
-
3
#include <iostream> #include <stack> #include <string> using namespace std; bool isMatching(char left, char right) { return (left == '[' && right == ']') || (left == '(' && right == ')'); } string checkBracketMatching(string s) { stack<char> st; for(char c : s) { if(c == '[' || c == '(') { st.push(c); } else if(c == ']' || c == ')') { if(st.empty() || !isMatching(st.top(), c)) { return "Wrong"; } st.pop(); } } if(st.empty()) { return "OK"; } else { return "Wrong"; } } int main() { string s; cin >> s; cout << checkBracketMatching(s) << endl; return 0; }
AC
-
-1
这道题可以用C++STL(已AC,放心食用)
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; stack<char> stk; for (int i = 0; i < s.length(); ++i) { if (s[i] == '(' || s[i] == '[') // 左括号入栈 stk.push(s[i]); else if (s[i] == ')' || s[i] == ']') { if (stk.empty() || s[i] == ')' && stk.top() != '(' || s[i] == ']' && stk.top() != '[') // 栈空或括号不配对 { cout << "Wrong"; // 无法配对 return 0; } else stk.pop(); } } if (stk.empty()) // 如果栈不空,则无法配对 cout << "OK"; else cout << "Wrong"; return 0;
- 1
信息
- ID
- 2055
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 5
- 标签
- (无)
- 递交数
- 186
- 已通过
- 67
- 上传者