Leetcode c语言-Longest Palindromic Substring

来源:互联网 发布:中国保险保险网络大学 编辑:程序博客网 时间:2024/06/05 22:56

Title:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

Example:

Input: "cbbd"Output: "bb"

题目是要找到字符串中的最长的回文字符串。并输出该回文字符串。


这道题目最暴力的方法就是利用嵌套循环遍历所有的字符,先找到一头一尾一样的,然后再判断中间的字符是不是对称。但这种方法的时间复杂度很高:O(n^3),提交会出现:Time Limit Exceeded,超出时间限制。但对于实际应用,这种方法也可以应用,c代码如下:

Solutions1:

char* longestPalindrome(char* s) {    int len=0;    int j,m,n;    int i = 0;    int last_i=0;    int last_j=0;      char *result;            while (s[len]) {        len++;    }        printf("%d\n",len);    while (s[i] == s[i+1]) {        i++;    }    printf("%d\n",i);    if (i == len -1)        return s;        for (i = 0; i < len; i++) {        for (j = len-1; j > i; j--) {            if (s[i] == s[j]) {                if ((j - i - 1) == 0 || (j - i - 1) == 1) {                      if ((last_j - last_i) < (j - i)) {                        last_j = j;                        last_i = i;                        }                }                else {                                        for (m = 1; m <= (int)((j - i - 1)/2); m++) {                        if (s[i+m] != s[j-m]) {                            break;                        }                        if (((last_j - last_i) < (j - i)) && (m == (int)((j - i - 1)/2))) {                        last_j = j;                        last_i = i;                        }                    }                }            }        }    }    s[last_j+1] = 0;    return s+last_i;    }



那么另一种解法是从中间往两边查找,判断左边和右边的字符是不是相同即可,这种方法只需遍历一遍字符串,时间复杂度比上一种方法要少:O(n^2)。先贴出代码:

Solutions2:

int findOdd(char* s,int center){      int i=center-1,j=center+1;      while(i>=0 && s[j]){          if(s[i]!=s[j])return j-1;          i--;j++;      }      return j-1;  }  int findEven(char* s,int center){      int i=center,j=center+1;      while(i>=0 && s[j]){          if(s[i]!=s[j]){              return j-1;          }          i--;j++;      }      return j-1;  }  char* longestPalindrome(char* s) {      int i=0,end,Max=1,Maxf=0,Maxe=0;      for(i=0;s[i];i++){          end=findOdd(s,i);          if(Max<(end-i)*2+1){              Max=(end-i)*2+1;              Maxf=i+i-end;Maxe=end;          }          end=findEven(s,i);          if(Max<(end-i)*2){              Max=(end-i)*2;              Maxf=i+i+1-end;Maxe=end;          }      }      s[Maxe+1]=0;      return s+Maxf;  }  

该算法,首先利用for遍历一遍字符串,然后,判断是奇数回文字符串还是偶数回文字符串。然后分别进行处理。


原创粉丝点击