Unusual Competitions
#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
#include <map>
const int maxn = 1e6 + 7;
typedef long long ll;
using namespace std;
const ll mod = 10007;
const long double pi = 3.1415926535897932384626433832795;
queue<char> q;
int vis[3][maxn];
map<int,bool>mp;
int a[maxn], b[maxn];
string s, s1;
int solve(){
int flag = 1;
int n = s1.size();
stack<char>st;
for (int i = 0; i < n; i++){
if (s1[i] == '(')
st.push(s1[i]);
else{
if (st.empty()){
flag = 0;
continue;
}
if (s1[i] == ')' && st.top() == '(')
st.pop();
}
}
if (!st.empty())
flag = 0;
return flag;
}
int main(){
int n;
cin >> n >> s;
int l = 0, r = 0;
int ans = 0;
for (int i = 0; i < n; i ++){
if (s[i] == '(')
l ++, s1 += '(';
if (s[i] == ')')
r ++, s1 += ')';
if (l == r){
if (solve() == 0)
ans += (l+r);
s1 = "";
l = 0;
r = 0;
}
}
if (l != r)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
大概思路就是判断左右括号的数量,并保存,当左右括号相等时,判断他们是否合法,不合法就加左右括号的数量。在循环后判断左右括号是否相等即可。