26B--Regular Bracket Sequence

题目

A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 10^6.

Output

Output the maximum possible length of a regular bracket sequence.

Examples
input
(()))(
output
4
input
((()())
output
6
题意:给出一串括号,找出其最大匹配的个数。
解题思路: 利用栈的操作,当为’(‘时,将其压栈,当为’)‘时,判断是否为空,如果不为空,进行弹栈,并进行count+=2;还有另外一种方法,判断字符串每位字符为’('时,计算其个数(k++),否则判断k>0?,如k>0;进行k–,并进行count+=2;最终输出结果。
AC-Code(Stcak方法)
import java.util.Scanner;
import java.util.Stack;

public class ACM26B {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		Stack<Character> stack = new Stack<Character>();
		int count = 0;
		for(int i = 0 ;i<s.length();i++)
		{
			if(s.charAt(i)=='(')
			{
				stack.push('(');
			}
			else if(!stack.isEmpty())
			{
				stack.pop();
				count+=2;
			}
		}
		System.out.println(count);
		
		sc.close();
	}

}
AC-Code(普通方法)
import java.util.Scanner;
public class ACM26B {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();

		int k=0,count=0;
		for(int i = 0;i<s.length();i++)
		{
			if(s.charAt(i)=='(')
			{
				k++;
			}
			else {
				if(k>0)
				{
					k--;
					count+=2;
				}
			}
		}
		System.out.println(count);
		sc.close();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值