LeetCode题解:Longest Palindromic Substring

Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

思路:

只想到一个O(n^2)的解法。就是从左到右扫描起点,同时从右向左扫描终点。也可以考虑记录从右向左各个字符的位置,方便搜索。

题解:

class Solution {
public:
    bool check_palindrome(string& s, int i, int j)
    {
        while(i<j) if (s[i++]!=s[j--]) return false;
        return true;
    }
    
    string longestPalindrome(string s) {
        int i=0;
        int j=s.size()-1;
    
        int maxlen=0;
        int start=0;
    
        while(i<s.size())
        {
            j=s.size()-1;
            while(j>=i)
            {
                if (s[j]==s[i])
                    if (check_palindrome(s,i,j))
                    {
                        if (maxlen<=j-i+1)
                        {
                            maxlen=j-i+1;
                            start=i;
                        }
                        break;
                    }
                j--;
            }
            i++;
        }
        return s.substr(start, maxlen);
    }
};


你可能感兴趣的:(LeetCode)