一个完整的括号字符串定义规则如下:
1、空字符串是完整的。
2、如果s是完整的字符串,那么(s)也是完整的。
3、如果s和t是完整的字符串,将它们连接起来形成的st也是完整的。
例如,"(()())", ""和"(())()"是完整的括号字符串,"())(", "()(" 和 ")"是不完整的括号字符串。
牛牛有一个括号字符串s,现在需要在其中任意位置尽量少地添加括号,将其转化为一个完整的括号字符串。请问牛牛至少需要添加多少个括号。
输入包括一行,一个括号序列s,序列长度length(1 ≤ length ≤ 50). s中每个字符都是左括号或者右括号,即'('或者')'.
输出一个整数,表示最少需要添加的括号数
(()(()
2
public static void main(String args[]){ Scanner in = new Scanner(System.in); String str = in.nextLine(); //count计数多出来的"(",n计数字符串最前面的")" int count = 0, n=0; for(int i = 0; i < str.length(); i++){ if(str.charAt(i) == '('){ count++; } if(str.charAt(i) == ')') { if(count == 0){ n++; }else{ count--; } } } System.out.println(count+n); }
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String s= sc.nextLine(); int l=s.length(); int Count=0; int right =0; char[]c=new char[l]; c= s.toCharArray(); for(int i=0;i<l;i++) { //if(s.charAt(i)=='(') if( c[i]=='(') Count++; else if( c[i]==')'&&Count>0) Count--; else right++; } System.out.println(Count+right); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cnt=0, bracket=0, i; String input = sc.nextLine(); for (i=0; i<input.length(); ++i) { if (input.charAt(i) == '(') bracket++; else bracket--; if (bracket < 0) { bracket = 0; cnt++; } } System.out.println(cnt += bracket); } }
/*采用栈后进先出的思想匹配左右括号,遇到'('顶入栈,即count++,遇到')'栈顶出栈,即count--每次count都与max比较大小,最大的数即为括号深度 */ import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0,max = 1;
for(int i = 0; i < str.length()-1; i++){
if(str.charAt(i) == '('){
count ++;
}
if(str.charAt(i) == ')'){
count--;
}
if(count > max){
max = count;
}
}
System.out.println(max);
}
}