Longest Palindromic Substring

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.

class Solution {
public:
    string longestPalindrome(string s) {
        string result;
	    int n = s.size();
	    if (n < 1)
	    {
		    return result;
	    }

	    int begin = 0;
	    int maxLen = 1;
	    for (int i = 0; i < n;)
	    {
		    if (n-i <= maxLen/2)
		    {
			    break;
		    }

		    int left = i;
		    int right = i;
		    while (right < n-1 && s[right] == s[right+1])
		    {
			    right++;
		    }

		    i = right+1;
		    while (left > 0 && right < n-1 && s[left-1] == s[right+1])
		    {
			    left--;
			    right++;
		    }
		    int temp = right-left+1;
		    if (temp > maxLen)
		    {
			    maxLen = temp;
			    begin = left;
		    }
	    }

	    return s.substr(begin, maxLen); 
    }
};


你可能感兴趣的:(Longest Palindromic Substring)