题目
You are given a string s, consisting of brackets of two types: ‘(’, ‘)’, ‘[’ and ‘]’.
A string is called a regular bracket sequence (RBS) if it’s of one of the following types:
empty string;
‘(’ + RBS + ‘)’;
‘[’ + RBS + ‘]’;
RBS + RBS.
where plus is a concatenation of two strings.
In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.
What is the maximum number of moves you can perform?
Input
The first line contains a single integer t (1≤t≤1000) — the number of testcases.
Each of the next t lines contains a non-empty string, consisting only of characters ‘(’, ‘)’, ‘[’ and ‘]’. The total length of the strings over all testcases doesn’t exceed 2⋅105.
Output
For each testcase print a single integer — the maximum number of moves you can perform on a given string s.
题意
一个简单的括号匹配问题,问有多少对合法的括号
题解
扫一遍就好,每当遇到右括号,看有无匹配度的左括号即可
AC代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t; cin >> t;
while(t--){
string str; cin >> str;
int len = str.length();
int num1 = 0, num2 = 0;
int res = 0;
for(int i = 0; i < len; i++){
if(str[i] == '(')
num1++;
if(str[i] == ')'){
if(num1){
num1--;
res++;
}
}
if(str[i] == '[')
num2++;
if(str[i] == ']'){
if(num2){
num2--;
res++;
}
}
}
printf("%d\n", res);
}
return 0;
}