1. 程式人生 > >leetcode 5最長迴文子串(1)

leetcode 5最長迴文子串(1)

第一種就是從中間開始判斷,分為兩種情況,長度為奇數還是偶數,但是時間複雜度為O(n^2),程式碼如下

char* longestPalindrome(char* s) {
   int low,length,high,j,k;
   printf("%s\n",s);
   length=strlen(s);
   static char s1[1005];
   low=high=0;
   j=k=0;
   for(int i=0;i<length;i++){  
       if(s[i-1]==s[i+1]){
         j=i-1;
         k=i+1;
         while(s[j]==s[k]&&j>=0&&k<length){
           j--;
           k++;
         }
       }
        if(k-j-1>high-low+1){
           high=k-1;
           low=j+1;
       }
       if(s[i]==s[i+1]){
       j=i-1;
       k=i+2;
       while(s[j]==s[k]&&j>=0&&k<length){
            j--;
           k++;
         }
       }
       if(k-j-1>high-low+1){
           high=k-1;
           low=j+1;
       }
   }
    printf("%d %d\n",low,high);
    k=0;
    for(int i=low;i<=high;i++,k++){
        s1[k]=s[i];
    }
    s1[k]='\0';
   return s1;
}

下次在實現https://blog.csdn.net/qq_32354501/article/details/80084325?utm_source=copy