1. 程式人生 > >26B--Regular Bracket Sequence

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