1. 程式人生 > >Longest Palindromic Substring 找最長的迴文子字串

Longest Palindromic Substring 找最長的迴文子字串

所謂迴文字串,就是一個字串,從左到右讀和從右到左讀是完全一樣的。比如"level" 、 “aaabbaaa”

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"
個人(菜鳥)思路:

兩個for迴圈,外層i從左向右,內層j右向左。如果s[i]==s[j],遍歷i->j,是迴文字串就記錄下來,不是的話繼續j--。

C:

char* longestPalindrome(char* s) {
    int maxlength = 0,length,temp = 1;
    int i = 0,j = 0,x = 0,k = 0;
    int i_flag = 0,j_flag = 0,flag;

    while(s[i] != NULL){
        i++;
    }
    length = i;

    for(i = 0 ;i < length; i++){
        for(j = length - 1;j > i; ){
            if(s[i] == s[j]){
                flag = true;
                x = i;
                k = j;
                while(x <= k){
                    if(s[x] != s[k])
                        flag = false;
                    x++;
                    k--;
                }
                if(flag == true){
                    if(maxlength < (j - i + 1)){
                        i_flag = i;
                        j_flag = j;
                        maxlength = (j - i + 1);
                    }
                    break;
                } else{
                    j--;
                }
            }else{
                j--;
            }
        }
    }

    if(maxlength == 0){
        char *non_result = (char *)malloc(sizeof(char));
        non_result[0] = s[0];
        return non_result;
    }else{
        if(maxlength == length)
            return s;
        else{
            char *result = (char *)malloc(sizeof(char)* (j_flag - i_flag + 1));

            for(i = i_flag, j = 0; i <= j_flag ; i++,j++){
                result[j] = s[i];
            }
            result[j] = '\0';
            return result;
        }
    }
}