40 lines
1.1 KiB
C++
40 lines
1.1 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
using namespace std;
|
|
//确定每个节点要干什么
|
|
bool dfs(const string& s, int l, int r) {
|
|
if (l > r) return true; // 空串平衡
|
|
if (l == r) return false; // 单个字符不平衡
|
|
|
|
// 必须匹配类型
|
|
char open = s[l];
|
|
char close = (open == '(') ? ')' : (open == '[') ? ']' : 0;
|
|
if (close == 0) return false; // 非括号字符
|
|
|
|
int cnt = 0;
|
|
int p = -1;
|
|
for (int i = l; i <= r; i++) {
|
|
if (s[i] == '(' || s[i] == '[') cnt++;
|
|
if (s[i] == ')' || s[i] == ']') cnt--;
|
|
if (cnt == 0) {
|
|
p = i; // 找到匹配的右括号
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (p == -1) return false; // 没找到匹配
|
|
if (s[p] != close) return false; // 类型不匹配(第一个和最后一个字符匹配)
|
|
|
|
// 内部和剩余区间递归
|
|
return dfs(s, l + 1, p - 1) && dfs(s, p + 1, r);
|
|
}
|
|
|
|
int main(){
|
|
string a;
|
|
while(true)
|
|
{
|
|
cin >> a;
|
|
dfs(a, 0, a.size() - 1) ? cout << "YES" << endl : cout << "NO" << endl;
|
|
}
|
|
return 0;
|
|
} |