首页 > 试题广场 >

缺失的括号

[编程题]缺失的括号
  • 热度指数:6027 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。

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


输出描述:
输出一个整数,表示最少需要添加的括号数
示例1

输入

(()(() 

输出

2 

python解法

a = input()
arr, res = [], 0
for i in a:
    if i == "(":  # 如果为左括号,直接扔进arr数组
        arr.append("(")
    else: # 此时为右括号
        if len(arr) > 0: # 如果有匹配的左括号,将arr中消除掉一个左括号。
            arr.pop(-1)
        else: #此时没有匹配的左括号,要手动添加一个。
            res += 1
print(res + len(arr)) # 最后结果还要加上数组中左括号的个数,因为要额外添加对应数量的右括号
发表于 2019-03-02 14:21:32 回复(0)
/*
    思路:类似栈的思想  左右括号相遇时可消除
         countL 记录最终正确括号消除后所剩的'('的数目
         countL 记录最终正确括号消除后所剩的')'的数目
*/
import java.util.*;
public class Main{
    public static void main(String[] args){
        try(Scanner in = new Scanner(System.in)){
            System.out.println(helper(in.nextLine()));
        }
    }
    public static int helper(String s){
        char[] cs = s.toCharArray();
        int countL = 0,countR = 0,i = 0;
        while(i < cs.length){
            if(cs[i] == '('){
                countL++;
            }else {
                // 遇到右括号时,若前面有左括号未匹配,则匹配消除   如果没有,则右括号数目加1
                if(countL != 0){
                    countL--;
                }else{
                    countR++;
                }
            }
            i++;
        }
        return countL + countR;
    }
}


发表于 2019-02-10 17:25:08 回复(2)

本套3道题的C++代码已挂到了我的GitHub(https://github.com/shiqitao/NowCoder-Solutions)
牛客网上的其他题目解答也在持续更新。

#include 
#include 
using namespace std;
int main()
{
    string str; cin >> str;
    int result = 0, num = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == '(') num++;
        else {
            if (num == 0) result++;
            else num--;
        }
    }
    cout << result + num << endl;
    return 0;
}
编辑于 2017-12-21 20:22:53 回复(0)

用两个变量count和need就可以搞定。

遍历字符串,当遇到左括号时,count++
遇到右括号时,count--
每当count=-1时,need++,表示缺失的左括号数
最后count + need就是所得结果

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int need = 0;
        int count = 0;
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '(') {
                count++;
            } else {
                count--;
            }
            if (count < 0) {
                count = 0;
                need++;
            }
        }
        System.out.println(need + count);
    }
}
发表于 2019-06-15 17:31:22 回复(0)
#include <iostream>
#include <stack>
using namespace std;
int main(){

    string str;
    cin >> str;
    int right = 0;
    stack<char> stac;
    for(int i = 0; i < str.size(); ++i){
        if(str[i] == ')' && (stac.empty() || stac.top() == ')')){
            ++right;
        }else if(str[i] == '('){
            stac.push(str[i]);
        }else if(str[i] == ')' && stac.top() == '('){
            stac.pop();
        }
    }
    cout << stac.size() + right << endl;;
    
    return 0;
}




发表于 2019-06-05 22:52:28 回复(0)
#include<stdlib.h>
#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
    string s;
    cin>>s;
    stack<char>st;
    int res=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='(')
            st.push(s[i]);
        else
        {
            if(st.empty())
                res++;
            else
                st.pop();
        }
    }
    if(!st.empty())
        res+=st.size();
    cout<<res<<endl;
    return 0;
}

发表于 2019-05-25 16:11:56 回复(0)
    private static int solve(String string) {
        int count = 0;
        LinkedList<Character> stack = new LinkedList<>();
        for (char c : string.toCharArray()) {
            switch (c) {
            case '(':
                stack.push(c);
                break;
            case ')':
                if (stack.isEmpty()) {
                    count++;
                } else {
                    stack.pop();
                }
                break;
            default:
                break;
            }
        }
        count += stack.size();
        return count;
    }

发表于 2019-04-01 15:33:51 回复(0)
aa=input()

lenth=len(aa)

k=0

count=0

for i in range(lenth):

    if(aa[i]== '(' ):

    k=k+1

elif((aa[i]== ')')&(k>0)):

    k=k-1

else:

    count=count+1

k=k+count

print(k)

Count多余的右括号,K记录多余的左括号;
发表于 2019-03-19 11:41:14 回复(0)
def bracket(b):
    while "()" in b:
        b = b.replace("()","")
    return len(b)

def brack(b):
    res = [b[0]]
    for i in range(1, len(b)):
        # 如果不添加res条件,会报请检查是否存在语法错误或者数组越界非法访问等情况
        if res and b[i] == ")" and res[-1] == "(":
            res.pop()
        else:
            res.append(b[i])
    return len(res)

if __name__ == "__main__":
    b = input()
    print(brack(b))

编辑于 2019-03-12 11:35:44 回复(0)
#include <bits/stdc++.h>

using namespace std;

int main()
{     string s;     while(cin>>s){         int n = s.length();         stack<char> S;         for(int i=0;i<n;i++){             if(s[i]=='(')                 S.push(s[i]);             else if(s[i]==')'){                 if(!S.empty() && S.top()=='(')                     S.pop();                 else                     S.push(s[i]);                             }         }         cout<<S.size()<<endl;     }     return 0;
}

发表于 2019-02-23 02:26:44 回复(0)
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
char s[100];
int dp[100][100],i,j,n,k;
int main(){
    scanf("%s",s),n=strlen(s);
    for(i=n-1;i>=0;i--)
        for(j=i;j<n;j++)
            if(i==j) dp[i][j]=1;
            else if(i+1==j){
                if(s[i]=='('&&s[j]==')') dp[i][j]=0;
                else dp[i][j]=2;
            }else{
                dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1;
                if(s[i]=='('&&s[j]==')')
                    dp[i][j]=min(dp[i][j],dp[i+1][j-1]);
                for(k=i;k<j;k++) dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
            }
    printf("%d\n",dp[0][n-1]);
}

发表于 2017-11-28 22:55:00 回复(0)
package main

import (
    "fmt"
)

func main() {
    var s string
    fmt.Scan(&s)
    stk:=[]byte{}
    for _,ch:=range []byte(s){
        if len(stk)>0&&stk[len(stk)-1]=='('&&ch==')'{
            stk=stk[:len(stk)-1]
        }else{
            stk=append(stk,ch)
        }
    }
    fmt.Print(len(stk))
}

发表于 2023-03-21 00:43:57 回复(0)
写一个简单栈表就ok了
#include<stdio.h>
#include<string.h>
int main()
{
    char a[1000];
    while (gets(a))
    {
        int i,j=-1;
        char t[1000];
        for(i=0;i<strlen(a);i++)
        {
            if(a[i]=='(')
            {
                t[++j]=a[i];
            }
            else if(a[i]==')')
            {
                if(t[j]=='(')
                {
                    j--;
                }
                else
                {
                    t[++j]=a[i];
                }
            }
        }
        printf("%d\n",j+1);
    }
    return 0;
}


发表于 2021-09-15 09:43:45 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s;
	cin >> s;
	int sum = 0;
	stack<char> sc;
	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == '(')sc.push(s[i]);
		else if (s[i] == ')' && !sc.empty())sc.pop();
		else if (s[i] == ')'&&sc.empty()) sum++;
	}
	cout << sum + sc.size();
}

发表于 2020-04-28 14:22:31 回复(0)
其实很简单,反复循环去掉所有的 (),剩下几个 单独的半个括号,就补充几个喽
s=input()
while s.find('()')!=-1:
    s=s.replace('()','')
print(len(s))


发表于 2020-02-05 19:04:11 回复(0)
a=input()
while True:
    if '()' in a:
        a=a.replace('()','')
    else:
        break
print( len(a))

发表于 2019-08-22 21:25:50 回复(0)

删去所有的左右括号对,再求字符串长度即可

#include <stdio.h>
#include <string.h>

char s[60];

int main()
{
	int i=0,j,k,flag;
	for(gets(s);s[i];i++)
	{
		if(s[i]=='(')
		{
			flag = 0;
			for(j=i+1;s[j];j++)
				if(s[j]==')')
				{
					flag = 1;
					break;
				}
			if(flag)
			{
				for(k=j;s[k];k++)
					s[k] = s[k+1];
				for(k=i;s[k];k++)
					s[k] = s[k+1];
				i--;
			}
		}
	}
	printf("%d\n",strlen(s));
	return 0;
}


发表于 2019-08-22 08:57:40 回复(0)
import java.util.Scanner;
import java.util.Stack;

/**
 * @author Shumao
 * @date 2019/6/24 16:37
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < line.length(); i++) {
                char ch = line.charAt(i);
                if (!stack.empty() && '(' == stack.peek() && ')' == ch) {
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
            System.out.println(stack.size());
        }
        scanner.close();
    }

}

发表于 2019-06-24 17:04:57 回复(0)
""" 思路有2个: 1.有效的括号表达式应该是左括号数量和有括号数量相等,二者之差就表示需要添加的括号数量 
2.按照判断是否是有效括号的思路,左括号进栈,遇到右括号出栈,最后栈中剩余的元素个数(全是左括号) 即是需要添加 的括号数量 """ 
string = input() 
def get_mini_nums1(): 
    # 通过60%有问题 
    left_brace = string.count('(') 
    right_brace = string.count(')') 
    return abs(left_brace-right_brace) 

def get_mini_nums2(): 
    stack = [] 
    count = 0 
    for char in string: 
        if char=='(': 
            stack.append(char) 
        else: 
            if stack: 
                stack.pop() 
            else: 
                # 如果第一个是右括号,栈为空 
                # 则需要补充一个左括号 
                count += 1 
    count += len(stack) 
    return count 
if __name__ == '__main__': 
    print(get_mini_nums2())

编辑于 2019-06-17 22:47:53 回复(0)
import java.util.Scanner;
public class Main{
           public static void main(String[] args) {
         Scanner sc=new Scanner(System.in);
         while(sc.hasNext()){
          String s=sc.nextLine();
          int n=getResult(s);
          System.out.println(n);
         }
  }
  public static int getResult(String s) {
      char[] cc=s.toCharArray();
      int f=0;
      int k=0;
      int n=0;
      int m=0;
      int flag=0;
      if(s!=null){
     for(int i=0;i<cc.length;i++){
      
      if(String.valueOf(cc[i]).equals("(")&flag!=2){
       flag=1;
       f++;
     
      }else if(String.valueOf(cc[i]).equals(")")&flag!=0){
       flag=2;
       k++;
     
      }else if(String.valueOf(cc[i]).equals("(")&flag==2){
       if(k>f){
        m=m+Math.abs(f-k);
       
        f=1;
        k=0;
       }else{
        f++;
       }
     
      }else if(String.valueOf(cc[i]).equals(")")&flag==0){
       m++;
      }
      if(i==cc.length-1){
      
       m=m+Math.abs(f-k);
      
      }
     }
     
     n=m;
    
      }
   return n;
  }
}

发表于 2019-06-09 21:46:36 回复(0)