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

HDU 1544 Palindromes(回文子串)

时间:2015-04-26 22:43:22      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1544

 

问题分析:

问题要求求出字符串的连续子串中的回文子串个数。首先,需要区分连续子串与子序列的区别。

连续子串为连续的字符组成的字符串;子序列需要满足在子序列中出现的字符的相对顺序与字符串中出现的相对顺序相同。

问题的解法:根据回文子串的长度分为奇数与偶数分为两种可能;

1.当回文子串长度为奇数时,中间的字符为任意字符,取除了字符串最左边与最右边的字符的其他字符,通过向两边拓展来判断

奇数回文子串的个数。

2.当回文子串长度为偶数时,通过选取除了最后一个字符外的其他字符作为基本字符,向两边拓展来求取偶数的回文子串的个数。

3.将偶数的回文子串的个数与奇数的回文子串的个数,字符串的字符个数相加即为所求。

 

 

代码如下:

#include <stdio.h>
#include <string.h>

const int MAX_N = 5000 + 10;
char str[MAX_N];

int main()
{
    while (scanf("%s", str) != EOF)
    {
        int ans = 0;
        int len = strlen(str);
        int left, right;

        for (int i = 1; i < len - 1; ++ i)
        {
            left = i - 1;
            right = i + 1;
            while (left >= 0 && right < len && str[left] == str[right])
                    ans++, left--, right++;
        }

        for (int i = 0; i < len - 1; ++ i)
        {
            if (str[i] == str[i+1])
            {
                ans++;
                left = i - 1;
                right = i + 2;
                while (left >= 0 && right < len && str[left] == str[right])
                        ans++, left--, right++;
            }
        }
        printf("%d\n", ans + len);
    }
    return 0;
}

HDU 1544 Palindromes(回文子串)

标签:

原文地址:http://www.cnblogs.com/tallisHe/p/4458463.html

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