您的位置:首页 > 其它

最长合法括号序列

2013-03-19 20:55 260 查看
题目描述:

给你一个长度为N的,由’(‘和’)’组成的括号序列,你能找出这个序列中最长的合法括号子序列么?合法括号序列的含义便是,在这个序列中,所有的左括号都有唯一的右括号匹配;所有的右括号都有唯一的左括号匹配。例如:((()))()()便是一个长度为10的合法括号序列,而(()))( 则不是。

需要你求解的是,找出最长的合法括号子序列的长度,同时找出具有这样长度的序列个数。

输入:

测试数据包括多个,每个测试数据包含两行:

第一行为一个整数N,其中N不会超过10^6。

第二行为一个长度为N的字符串,这个字符串由左括号’(‘和右括号’)'组成。

输出:

对应每个测试案例,输出一行,其中包含两个整数,分别代表最长合法括号序列的长度和个数,中间由空格隔开。若没有合法的子序列存在,则返回0 1。

样例输入:

6

(())()

3

))(

样例输出:

6 1

0 1
import java.util.Stack;

public class BlancketMatch {

public static void maxBlancketMatch(String input) {

Stack<Entry> stack = new Stack<Entry>();
int[] array = new int[input.length()];
int max = 1;
int count = 0;

for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ')') {
if (!stack.isEmpty()) {
array[i] = 1;
array[stack.peek().getPosition()] = 1;
stack.pop();
}else {
array[i] = 0;
}
}else if (input.charAt(i) == '(') {
stack.push(new Entry(input.charAt(i), i));
array[i] = 0;
}else {
System.err.println("Invalid input");
return;
}
}

for (int i = 1; i < array.length; i++) {
if (array[i] > 0 && array[i - 1] > 0) {
array[i] += array[i - 1];
}
}

for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
if (max == 1) {
System.out.println("0 1");
return;
}

for (int i = 0; i < array.length; i++) {
if (array[i] == max) {
count++;
}
}

System.out.println("" + max + " " + count);
}

public static class Entry {

private char ch;
private int position;

Entry(char ch, int position) {
this.ch = ch;
this.position = position;
}

public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public char getCh() {
return ch;
}
public void setCh(char ch) {
this.ch = ch;
}
}

public static void main(String[] args) {
BlancketMatch.maxBlancketMatch("(()(()(");
BlancketMatch.maxBlancketMatch("(())()");
BlancketMatch.maxBlancketMatch("))(");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: