选择一对非重叠子串的方法的数量

时间:2016-10-12 08:17:02

标签: algorithm performance dynamic-programming

给定一个字符串s,预计会找到选择一对非重叠子串的方法的数量。 例如,在字符串abcdcefdfdio中,一种方法是选择cdcdfd 我的方法是dp one:

    String s = sc.next();
    int n = s.length();
    int firstsum[] = new int[n];//firstsum[i] stores the number of palindromes in the substring (0...i)
    int[][] A = new int[n][n];//A[i][j]=1 denotes the substring (i...j) is a palindrome and =0 otherwise
    for(int i=0;i<n;++i)
    {
        firstsum[i]=0;
        for(int j=i;j<n;++j)
        {
            if(check(s.substring(i,j+1))==1)
            {
                A[i][j]=1;
            }
            else
                A[i][j]=0;
        }
    }
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<=i;++j)
        {
            if(A[j][i]==1)
                firstsum[i]++;
        }
        if(i>0)
            firstsum[i]+=firstsum[i-1];
    }
    int cnt=0;
    for(int i=1;i<n;++i)
    {
        for(int j=i;j<n;++j)
            cnt+=A[i][j]*firstsum[i-1];
    }
    System.out.print(cnt);//answer

solution正在运行,但超出了时间限制。在DP中是否有更好的方法?

1 个答案:

答案 0 :(得分:1)

删除A[i][j]填充循环。在最坏的情况下它是O(n^3)

试试这段代码。

String s = sc.next();
int n = s.length();
int firstsum[] = new int[n];//firstsum[i] stores the number of palindromes in the substring (0...i)
int[][] A = new int[n][n];//A[i][j]=1 denotes the substring (i...j) is a palindrome and =0 otherwise

for(int i=0;i<n;++i)
{
     A[i][i]=1;
}

for(int len=1;len<n;++len)
{
    for(int i=0;i<n-len;++i)
    {
        if( s.charAt(i)==s.charAt(i+len) && (i+1>=i+len-1 || A[i+1][i+len-1]==1) )
        {
            A[i][len]=1;
        }
        else{
            A[i][len]=0;
        }
    }
}


for(int i=0;i<n;++i)
{
    firstsum[i]=0;
    for(int j=0;j<=i;++j)
    {
        if(A[j][i]==1)
            firstsum[i]++;
    }
    if(i>0)
        firstsum[i]+=firstsum[i-1];
}
int cnt=0;
for(int i=1;i<n;++i)
{
    for(int j=i;j<n;++j)
        cnt+=A[i][j]*firstsum[i-1];
}
System.out.print(cnt);//answer