zoukankan      html  css  js  c++  java
  • 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 = 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
    ", ans + len);
        }
        return 0;
    }
  • 相关阅读:
    XML 浏览器支持
    浏览器中的XML
    C/C++中判断某一文件或目录是否存在
    C/C++程序员必须熟练应用的开源项目 -- 转
    VC 中窗口的销毁
    sql proc触发异常处理回滚
    为Array 添加indexOf
    Js的两种post方式
    sql 针对多个id或名称的分割和组合
    sql 查看语句的性能
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4458463.html
Copyright © 2011-2022 走看看