1. 程式人生 > >一個完整的括號字串定義規則如下: 1、空字串是完整的。 2、如果s是完整的字串,那麼(s)也是完整的。 3、如果s和t是完整的字串,將它們連線起來形成的st也是完整的。

一個完整的括號字串定義規則如下: 1、空字串是完整的。 2、如果s是完整的字串,那麼(s)也是完整的。 3、如果s和t是完整的字串,將它們連線起來形成的st也是完整的。

一個完整的括號字串定義規則如下:
1、空字串是完整的。
2、如果s是完整的字串,那麼(s)也是完整的。
3、如果s和t是完整的字串,將它們連線起來形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括號字串,"())(", "()(" 和 ")"是不完整的括號字串。

牛牛有一個括號字串s,現在需要在其中任意位置儘量少地新增括號,將其轉化為一個完整的括號字串。請問牛牛至少需要新增多少個括號。

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
int main()
{
    int max_deep = 0;
    stack<char>  count_left , count_right ;
    char s;
    while((s = getchar()) != '\n'){
        if(s == '('){
            count_left.push('(');
        }else{
            if(count_left.empty()){
                count_right.push(')');
            }
            else{
                count_left.pop();
            }
        }
    }
    cout << count_left.size() + count_right.size() << endl;
    return 0;
}

上面這個是要求稍微有難度的問題。有的類似題目比較簡單:

要求是:"(()())", ""和"(())()"是完整的括號字串,不會出現非法字串或者括號不匹配的問題。

如果這樣的話程式碼就僅僅小小的改動就可:

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
	int max_deep = 0;
	int count_sign = 0;
	char s;
	while ((s = getchar()) != '\n'){
		if (s == '('){
			count_sign++;
			if (max_deep < count_sign){
				max_deep = count_sign;
			}
		}
		else{
			count_sign--;
		}
	}
	cout << max_deep << endl;
	return 0;
}