CSU 1271: Brackets Sequence(括号匹配问题)

题目:

Description

Let us define a regular brackets sequence in the following way:

1. Empty sequence is a regular sequence.

2. If S is a regular sequence, then (S) is a regular sequence.

3. If A and B are regular sequences, then AB is a regular sequence.

For example, these sequences of characters are regular brackets sequences: (), (()), ()(), ()(()), ((())())().

And all the following character sequences are not: (, ), ((), ()), ())(, (()(, ()))().

A sequence of characters ‘(‘ and ‘)’ is given. You can insert only one ‘(‘ or ‘)’ into the left of the sequence, the right of the sequence, or the place between any two adjacent characters, to try changing this sequence to a regular brackets sequence.

Input

The first line has a integer T (1 <= T <= 200), means there are T test cases in total.

For each test case, there is a sequence of characters ‘(‘ and ‘)’ in one line. The length of the sequence is in range [1, 105].

Output

For each test case, print how many places there are, into which you insert a ‘(‘ or ‘)’, can change the sequence to a regular brackets sequence.

What’s more, you can assume there has at least one such place.

Sample Input

4
)
())
(()(())
((())())(()

Sample Output

1
3
7
3

题意:

给定一个括号串,只需插入1个括号即可全部匹配

求有多少个地方可以插入1个括号使得全部匹配成功

思路:

首先,如何判断一个括号串是否完全匹配?

用数组num记录,num[i]表示前i个字符中,)和(的数量差

如果num[i]全部不超过0,而且最后一项为0,那么就可以完全匹配,反之亦然。

所以本题的答案是:

如果num[i]中有出现1,那么第一个1的位置就是答案

否则,最后一个0的位置与括号串长度之差就是答案

代码:

#include<iostream>
#include<string.h>
using namespace std;

char ch[100005];
int num[100005];//前i个字符中)和(的数量差

int main() {
	int T, len;
	cin >> T;	
	while (T--)
	{
		cin >> ch + 1;
		len = strlen(ch+1);
		num[0] = 0;
		int i, k0 = 0;
		for (i = 1; i <= len; i++)
		{
			if (ch[i] == '(')num[i] = num[i - 1] - 1;
			else num[i] = num[i - 1] + 1;
			if (num[i] > 0)
			{
				cout << i << endl;
				break;
			}
			if (num[i] == 0)k0 = i;
		}
		if (i > len)cout << len - k0 << endl;
	}
	return 0;
}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/nameofcsdn/article/details/79756621
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞