leetcode 5 -- Longest Palindromic Substring

来源:互联网 发布:北京朝阳教育网络视频 编辑:程序博客网 时间:2024/06/05 21:58

题目

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

题意

从字符串中找出最长回文子串,将其另存新串,返回指针

思路

回文串只有两种类型,长度为偶数和长度为奇数型
遍历字符串s:
–奇数型:以s[i]为中心,向两边延伸判断
–偶数型:以s[i]和s[i+1]为起点分别延伸
每次判断完后,记录子串

代码

char* longestPalindrome(char* s) {    char *a=(char *)malloc(sizeof(char)*1001);//开辟空间    int i,j,k,max = 0;    for(i=0;i<strlen(s);i++)    {        j=0;        while(s[i-j] == s[i+j] && i-j>=0 && i+j < strlen(s))//奇数型        {            j++;        }        if(j*2-1 > max)        {            max = j*2 - 1;            for(k=0;k<j*2-1;k++)            {                a[k]=s[k+i-j+1];            }            a[k]='\0';        }        j=0;        while(s[i-j] == s[i+j+1] && i-j>=0 && i+j+1<strlen(s))//偶数型        {            j++;        }        if(j*2 > max)        {            max = j*2;            for(k=0;k<j*2;k++)            {                a[k]=s[k+i-j+1];            }            a[k]='\0';        }    }    return a;}
0 0
原创粉丝点击