algorithm - 选择一对不重叠的回文子串的方法数

标签 algorithm performance dynamic-programming

给定一个字符串s,期望找到选择一对不重叠的回文子串的方法的数量。
例如在字符串 abcdcefdfdio 中,一种方法是选择 cdcdfd
我的方法是 dp 方法:

    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 中?

最佳答案

删除 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

关于algorithm - 选择一对不重叠的回文子串的方法数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39993713/

相关文章:

mysql - 为什么 COUNT() 从大表查询比 SUM() 快得多

algorithm - 矩阵的每一行和每一列恰好有一个值

java - 两个整数一位一位地相减

python - Python中数组的多线程求和

performance - 为什么即使未打开分析,AQTime 也会减慢执行速度?可以采取什么措施吗?

algorithm - 如何使用具有可连接输入整数的动态编程来确定最长的递增子序列

algorithm - 修改树上的动态规划

performance - 在单向链表中找到指向节点 M 步骤尾部的指针的算法

algorithm - 给定一个字典和一个字母列表,找出所有可以用这些字母组成的有效单词

algorithm - 为什么这个动态规划递归关系是正确的?