C. Move Brackets(水题)

题意:给括号配对,像“(())”,"()",都能直接配对,像“)(”这种就需要反转一次,输入偶数个“()”,有一半“(”,有一半“)”,求需要反转的次数。

题解:感觉像之前那道01反转的题,可以通过记录“)”和“(”出现的先后顺序和出现次数,来判断是否需要翻转。

ACcode:

int main()
{
int t, n;
string str;
cin >> t;
while (t--)
{
int a=0, ans=0;
cin >> n>>str;
for (int i = 0; i < n; i++)
{
if (str[i] == '(')
a++;
else if (str[i] == ')')
a--;
if (a < 0)
{
ans++;
a = 0;//如果是负的,就说明“)”在“(”的前面而且不能够被抵消,进行计数。
}
}
cout << ans<<endl;
}
return 0;
}

原文地址:https://www.cnblogs.com/Uiney117/p/14312233.html