LeetCode OJ : 5 Longest Palindromic Substring

readyao發表於2015-12-15

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.


求字串中的最長迴文字串;
我的思路比較簡單,但是實現起來程式碼看著好亂。。。從第一個字元開始遍歷,直到最後一個字元,對每一個在index位置的字元進行判斷;
如果最長迴文字串是奇數,則判斷--index和++index是否相等;
如果最長迴文字串是偶數,則判斷index和++index是否相等;


class Solution {
public:
    string longestPalindrome(string s) {
        int maxlen = 0, index = 0, length;
        
        if (s.size() < 3){
            return s;
        }

        for (int i = 0; i < s.size()-1; ++i){
            length = findPalindrome(s, i);
            if (maxlen < length){
                maxlen = length;
                index = i;
            }
        }
        
        if (maxlen % 2 == 0)
            index = index - maxlen/2 + 1;
        else
            index = index - maxlen/2;
        string longestSubString(s, index, maxlen);
        return longestSubString;
    }

    int findPalindrome(string &s, int index){
        int l_index = index-1, r_index = index+1;
        int length1 = 1, length2 = 0;
        
        /*針對abvba這種奇數的情況*/
        while((s[l_index--] == s[r_index++]) && (r_index <= s.size())){
            length1 += 2;
        }
        
        /*針對abba這種偶數的情況*/
        l_index = index;
        r_index = index+1;
        while((s[l_index--] == s[r_index++]) && (r_index <= s.size())){
            length2 += 2;
        }
        
        return (length1 > length2) ?  length1 : length2;
    }
};



雖然程式碼看著惡習,但是執行效率還闊以,Runtime: 72 ms;我再找找其它的方法;


相關文章