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

5. Longest Palindromic Substring

时间:2019-01-05 21:39:40      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:malloc   substring   ret   --   ==   奇数   str   int   ges   

字符串遍历,从中间分出奇数回文和偶数回文两种情况不断更新长度。我一开陷入入误区把字符串分为奇偶结果偶数的可以过,基数的abb过不了。所以就是分析回文就好

char* longestPalindrome(char* s)
    {
        int len = strlen(s);
        if (len <= 1)
        { return s; }
        int start = 0;
        int maxlen = 0;
        for (int i = 1; i < len; i++)
        {
            int low = i - 1;
            int high = i;
            while (low >= 0 && high < len && s[low] == s[high])
            {
                low--;
                high++;
            }
            if (high - low - 1 > maxlen)
            {
                maxlen = high - low - 1;
                start = low + 1;
            }
            low = i - 1; high = i + 1;
            while (low >= 0 && high < len && s[low] == s[high])
            {
                low--;
                high++;
            }
            if (high - low - 1 > maxlen)
            {
                maxlen = high - low - 1;
                start = low + 1;
            }
        }
        char *arr = (char *)malloc(sizeof(char) * maxlen+1000);
        int i = 0;
        for (; i < maxlen; i++)
        {
            arr[i] = s[start++];
        }
        arr[i] = \0;
        return arr;
    }

 

5. Longest Palindromic Substring

标签:malloc   substring   ret   --   ==   奇数   str   int   ges   

原文地址:https://www.cnblogs.com/yuhaowang/p/10226036.html

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