26B--Regular Bracket Sequence

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z16160102042/article/details/83998878

题目

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();
	}
}

猜你喜欢

转载自blog.csdn.net/z16160102042/article/details/83998878