题解 CF1452C 【Two Brackets】

一道不难的题。

首先,我们明确一点:中括号和小括号并不冲突,我们可以把它们拆分成两个序列。

然后,我们发现要对答案有贡献,必须要有 “ $ ( $ ” 或 “ $ [ $ ”。所以,我们考虑使用栈来计算答案:

  • 遇到左括号时,入栈。
  • 遇到右括号时,将栈顶弹出。(注意保证栈内此时有元素)

Code

#include <iostream>
#include <cstring>
using namespace std;
int t;
string s;
int top,top2,ans;
int main()
{
	cin>>t;
	while(t--)
	{
		ans=0;top=top2=0;
		cin>>s;
		for(int i=0;i<s.length();i++)
		{
			if(s[i]=='(') top++;
			if(s[i]=='[') top2++;
			if(s[i]==')'&&top) top--,ans++;
			if(s[i]==']'&&top2) top2--,ans++;
		}
		cout<<ans<<endl;
	}
	return 0;
}
posted @ 2020-12-02 11:58  -lala-  阅读(152)  评论(0)    收藏  举报