HDU 1544 Palindromes(回文子串)

时间:2023-03-09 22:39:10
HDU 1544 Palindromes(回文子串)

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

问题分析:

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

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

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

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

奇数回文子串的个数。

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

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

代码如下:

#include <stdio.h>
#include <string.h> const int MAX_N = + ;
char str[MAX_N]; int main()
{
while (scanf("%s", str) != EOF)
{
int ans = ;
int len = strlen(str);
int left, right; for (int i = ; i < len - ; ++ i)
{
left = i - ;
right = i + ;
while (left >= && right < len && str[left] == str[right])
ans++, left--, right++;
} for (int i = ; i < len - ; ++ i)
{
if (str[i] == str[i+])
{
ans++;
left = i - ;
right = i + ;
while (left >= && right < len && str[left] == str[right])
ans++, left--, right++;
}
}
printf("%d\n", ans + len);
}
return ;
}