码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1544 Palindromes(回文字符子串)

时间:2017-11-30 21:44:26      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:rom   sam   ber   cee   put   test   for   lin   namespace   

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

题意:

问有多少个回文的子串。

题解:

从子串的长度考虑,长度为奇数的子串:它的中心只能在[1,len-2]范围内,分别从中心开始向两边扩展,遇到不回文就直接停止拓展。长度为偶数的子串:中心对称的左数范围在[0,len-2],分别以这中心的两个数向两边扩展。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    string s;
    while(cin>>s)
    {
        int ans=0;
        int len=s.length();
        for(int i=1;i<len-1;i++)
        {
            for(int j=1;i-j>=0&&i+j<len;j++)
            {
                if(s[i-j]==s[i+j])
                    ans++;
                else
                    break;
            }
        }
        for(int i=0;i<len-1;i++)
        {
            for(int j=0;i-j>=0&&i+j+1<len;j++)
            {
                if(s[i-j]==s[i+j+1])
                    ans++;
                else
                    break;
            }
        }
        cout<<ans+len<<endl;
    }
    return 0;
}

HDU 1544 Palindromes(回文字符子串)

标签:rom   sam   ber   cee   put   test   for   lin   namespace   

原文地址:http://www.cnblogs.com/orion7/p/7931794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!