爱奇艺校招笔试题 缺失的括号

题目描述

一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。

输入描述:

输入包括一行,一个括号序列s,序列长度length(1 ≤ length ≤ 50).
s中每个字符都是左括号或者右括号,即'('或者')'.

输出描述:

输出一个整数,表示最少需要添加的括号数

示例1

输入

(()(()

输出

2

这道题目可以用栈模拟,也可以简化版,直接运用括号序列的特点,空间复杂度为O(1)

括号序列有如下特点,如果将(看成是加一,)看成是-1, 那么再这个过程种,状态必须恒大于0,且最后等于0,这样就是匹配的,否则就是不匹配的。

有如下代码

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string str;
    cin>>str;
    int res=0;
    int temp = 0;
    for(auto c:str){
        if(c=='(')
            temp+=1;
        else if(c==')')
            temp+=-1;
        if(temp<0){
            temp=0;
            res++;
        }
    }
    cout<<res+temp<<endl;
}
#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string str;
    cin>>str;
    stack<char> st;
    int res=0;
    for(auto c:str){
        if(c=='(') st.push(c);
        else{
            if(st.empty())
                res++;         // 填一个右括号
            else
                st.pop();
        }
    }
    cout<<res+st.size()<<endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值