思路:模拟、这道题可以用栈去做,我一开始就去模拟了。遍历一遍那个字符串,遇到‘(’就cnt++;遇到‘)’cnt–;当cnt<0的时候就把cnt变成0,而move的次数就要加一。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t; cin>>t;
while(t--){
int n; cin>>n;
string s;cin>>s;
int cnt=0,count1=0;
for(int i=0;i<n;i++){
if(s[i]=='(') cnt++;
if(s[i]==')')
cnt--;
if(cnt<0) {
cnt = 0;
count1++;
}
}
cout<<count1<<endl;
}
return 0;
}
这道题还可以用栈去写:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t; cin>>t;
while(t--){
int n; string a;
cin>>n>>a;
stack<char>s;
for(int i=0;i<n;i++){
if(s.empty()) s.push(a[i]);
else if(s.top()=='('&&a[i]==')')
s.pop();
else s.push(a[i]);
}
cout<<s.size()/2<<endl;
}
return 0;
}