[LeetCode]Longest Palindromic Substring

 
 
class Solution {
//insert special character, then enumerate every character in workStr and record the max substring O(n^2)
public:
	string longestPalindrome(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		string workStr;
		workStr.resize(s.size()*2+1);
		for (int i = 0, j = 0; i < workStr.size(); ++i)
		{
			if(i%2 == 0)
				workStr[i] = '_';
			else workStr[i] = s[j++];
		}
		//find the maximum palindromic
		int maxLen = 0;
		int maxLeftIdx;
		int maxRightIdx;
		for (int i = 0; i < workStr.size(); ++i)
		{
			int leftIdx = i;
			int rightIdx = i;
			while (leftIdx > 0 && rightIdx < workStr.size()-1)
			{
				if (workStr[leftIdx-1] == workStr[rightIdx+1])
				{
					leftIdx--;
					rightIdx++;
				}
				else break;
			}
			if (rightIdx-leftIdx > maxLen)
			{
				maxLen = rightIdx-leftIdx;
				maxLeftIdx = leftIdx;
				maxRightIdx = rightIdx;
			}
		}
		maxLeftIdx /= 2;
		maxRightIdx /= 2;
		return s.substr(maxLeftIdx, maxRightIdx-maxLeftIdx);
	}
};

second time

class Solution {
//O(n), using the symmetric property of palindrome
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<char> workStr(2*s.size()+1);
        for(int i = 0, k = 0; i < workStr.size(); ++i)//...
        {
            if(i%2 == 0) workStr[i] = '\0';
            else workStr[i] = s[k++];
        }
        
        //populate p
        vector<int> p(workStr.size(), 0);
        int id = 0, mx = 0;
        for(int i = 1; i < workStr.size(); ++i)
        {
            p[i] = mx > i ? min(p[id*2-i], mx-i) : 1;
            while(i-p[i] >= 0 && i+p[i] < workStr.size() 
                  && workStr[i+p[i]] == workStr[i-p[i]]) p[i]++;
            if(i+p[i]-1 > mx)
            {
                mx = i+p[i]-1;
                id = i;
            }
        }
        //select the max 
        int maxLen = 0;
        int maxIdx = 0;
        for(int i = 0; i < p.size(); ++i)
            if(maxLen < p[i]-1) maxLen = p[i]-1, maxIdx = i;
        
        int startIdx = (maxIdx-maxLen)/2;
        return s.substr(startIdx, maxLen);
    }
};

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