leetcode algorithm practice questions - the longest palindromic substring (c language)

1. Description of the problem

String S A GIVEN, Find palindromic The longest in the substring by You S The maximum length that the ASSUME On May of 1000. IS S.
Example. 1:
the Input: "Babad"
the Output: "BAB"
Note: "ABA" Also IS A Valid answer.
Example 2:
the Input: "cbbd"
the Output: "bb"
source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-palindromic-substring
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

The first method: dynamic programming

Refer to the following article
https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/

char * longestPalindrome(char * s){
    char d[1000][1000] ={0};
    int i,j,curlen,start=0,maxlen=1;
    int length = strlen(s);
    for(j=1; j<length; j++){
        for(i=0; i<j; i++){
            if(s[i]==s[j])
                if(j-i<3)
                    d[i][j] = 1;
                else
                    d[i][j] = d[i+1][j-1];
            if(d[i][j]){
                curlen = j-i+1;
                if(curlen > maxlen){
                    maxlen = curlen;
                    start = i;
                }
            }
        }
    }
    if(length==0)
        maxlen = 0;
    *(s+start+maxlen) = 0;
    return s+start;
}

Here Insert Picture Description

The second method: Center diffusion method

void longestPart(char* s, int length, int left, int right, int* maxlen, int* start){
    int curlen;
    while(left >=0 && right<length){
            if(s[left]==s[right]){
                curlen =right-left+1;
                if(curlen > *maxlen){
                    *maxlen = curlen;
                    *start = left;
                }
                left--;
                right++;
            }
            else
                break;
            
    }
}
char * longestPalindrome(char * s){
    int i,start=0,maxlen=1;
    int length = strlen(s);
    for(i=0; i<length; i++){
        longestPart(s,length,i-1,i+1,&maxlen,&start);
    }
    for(i=0; i<length; i++){
        longestPart(s,length,i,i+1,&maxlen,&start);
    }   
    if(length==0)
        maxlen=0;  
    *(s+start+maxlen) = 0;
    

Here Insert Picture Description

Released six original articles · won praise 0 · Views 135

Guess you like

Origin blog.csdn.net/weixin_38072112/article/details/103979924