Description
We give the following inductive definition of a “regular brackets” sequence:
- the empty sequence is a regular brackets sequence,
- if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
- if a and b are regular brackets sequences, then ab is a regular brackets sequence.
- no other sequence is a regular brackets sequence
For instance, all of the following character sequences are regular brackets sequences:
(), [], (()), ()[], ()[()]
while the following character sequences are not:
(, ], )(, ([)], ([(]
Given a brackets sequence of characters a1a2 … an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i1,i2, …, im where 1 ≤ i1 < i2 < … < im ≤ n, ai1ai2 … aim is a regular brackets sequence.
Given the initial sequence ([([]])]
, the longest regular brackets subsequence is [([])]
.
Input
The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters (
, )
, [
, and ]
; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.
Output
For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
Sample Input
((()))
()()()
([]])
)[)(
([][][)
end
Sample Output
6
6
4
0
6 思路:动态规划,设dp[i][j]表示从i到j这段子串匹配的最大长度,则状态转移方程分两种情况,1.若从i到j-1这些字符中没有一个能与j匹配,则 dp[i][j] = dp[i][j-1],这是显然的;2.若从i到j-1中有字符能与j匹配(可能不止一个,并设他们组成集合为A),则 dp[i][j] = max(dp[i][j],dp[i][k-1]+dp[k+1][j-1]+2)(k属于集合A),加2是因为一旦匹配成功一次长度就会增加2.
#include<cstdio>
#include<cstring>
#include<iostream>
#define MAXN 111
using namespace std;
int dp[MAXN][MAXN];
char str[MAXN];
bool OK(int i,int j){return (str[i] == '(' && str[j] ==')') || (str[i] == '[' && str[j] == ']');}
int main(){
//freopen("in.cpp","r",stdin);
while(~scanf("%s",str) && strcmp(str,"end")){
memset(dp,,sizeof(dp));
int len = strlen(str);
for(int i = ;i < len;i ++){
for(int j = i-;j >= ;j--){
dp[j][i] = dp[j][i-];
for(int k = j;k < i;k ++)
if(OK(k,i)) dp[j][i] = max(dp[j][i],dp[j][k-] + dp[k+][i-]+);
}
}
printf("%d\n",dp[][len-]);
memset(str,,sizeof(str));
}
return ;
}