Brackets

题目:

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 i1i2, …, im where 1 ≤ i1 < i2 < … < im ≤ nai1ai2 … 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

题意:
给你一个长度不超过100的括号序列,求最长合法括号子序列的长度。合法的括号序列满足下列条件:
1.空的括号序列是合法的;
2.如果一个括号序列s是合法的,那么(s)和[s]都是合法的;
3.如果两个括号序列a和b都是合法的,那么ab也是合法的;
4.其他的括号序列都是不合法的。
例如:(), [], (()), ()[], ()[()]都是合法的,而(, ], )(, ([)], ([(]都是不合法的。


分析:
和求最长公共子串差不多,但是个人感觉最长公共子串比这个要容易理解
dp[i][j]表示在i和j区间的最长括号匹配数
如:
(xxx)ooo
在'('找到相匹配的')'的时候,字符串被分成两个部分,一个是中间的xxx,还有一个是')'是右边的ooo,我们假设此时与'('匹配的')'的位置为k,所以dp[i][j]就取d[i][j]和d[i][k-1]+d[k+1][j]+2的最大值

AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int maxn (int a,int b)
{
    return a>b?a:b;
}
int main()
{
    int dp[105][105];
    char a[105];
    while (scanf("%s",a)&&strcmp(a,"end"))
    {
        int len=strlen(a);
        memset(dp,0,sizeof(dp));
        for (int i=1;i<len;i++)  //区间间距
        {
            for (int j=0;j<len-1;j++) //起点
            {
                int k=i+j;     //终点
                dp[j][k]=dp[j+1][k];
                for (int m=j+1;m<=k;m++)
                    if ((a[j]=='('&&a[k]==')')||(a[j]=='['&&a[k]==']'))
                    dp[j][k]=max(dp[j][k],dp[j+1][m-1]+dp[m+1][k]+2);
            }
        }
        cout << dp[0][len-1] << endl;
    }
    return 0;
}

 

posted @ 2017-08-17 08:07  你的女孩居居  阅读(257)  评论(0编辑  收藏  举报