【ZOJ2744】Palindromes(dp)

题目链接

Palindromes


Time Limit: 2 Seconds      Memory Limit: 65536 KB


A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.

Now give you a string S, you should count how many palindromes in any consecutive substring of S.

Input

There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.

Proceed to the end of file.

Output

A single line with the number of palindrome substrings for each case.

Sample Input

aba
aa

Sample Output

4
3

【题意】

给定一个字符串,查找该字符串中回文串的个数。

【解题思路】

dp[i][j]表示第i给字符到第j个字符是否为回文串。

因为单个字符都是回文串,所以d[i][i]=true。现在只要考虑两种情况:

1)s[i]=s[j],那么只需dp[i+1][j-1]是回文串,dp[i][j]就是回文串

2)s[i]!=s[j],那么dp[i][j]肯定不是回文串。

【代码】

#include<bits/stdc++.h>
using namespace std;
char s[5005];
bool dp[5005][5005];
int main()
{
   while(~scanf("%s",s))
   {
        int l=strlen(s),k;
        int cnt=l;
        for (int i=0;i<l;i++)
            dp[i][i]=true;
        for (int i=1;i<l;i++)
        {
            for (int j=0;j<l-i;j++)
            {
                k=i+j;
                dp[j][k]=false;
                if (s[j]==s[k])
                {
                    if (j+1<k-1)
                    {
                        if (dp[j+1][k-1])
                        {
                            dp[j][k]=true;
                            cnt++;
                        }
                    }
                    else
                    {
                       dp[j][k]=true;
                       cnt++;
                    }
               }
           }
        }
        printf("%d\n", cnt);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/81837597
今日推荐