小明至少需要添加多少个括号

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

public class XiaoMing {

static String testStr = "1000101110";   //1 == ) 0 == (
static String testStr2 = "1000101110111";
public static void main(String[] args){
    System.out.println("hello");
    int need = needAddNumber(testStr);
    System.out.println("最少需要添加"+need+"个括号");

    int need2 = needAddNumber(testStr2);
    System.out.println("最少需要添加"+need2+"个括号");
}


public static int needAddNumber(String testStr){
    if (testStr == null || testStr.length() == 0){
        return 0;
    }
    int symbol1 = 0;
    int symbol0 = 0;
    for (int i = 0; i<testStr.length() ; ++i){
        if (testStr.charAt(i) == '1'){
            System.out.println("第"+i+"个是1");
            if (symbol0 <= 0){
                symbol1 += 1;
            }else {
                symbol0 --;
            }
        }else if (testStr.charAt(i) == '0'){
            System.out.println("第"+i+"个是0");
            symbol0 ++;
        }
    }
    return symbol0 + symbol1;
}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值