【LeetCode】43. Longest Palindromic Substring

题目描述(Medium)

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

题目链接

https://leetcode.com/problems/longest-palindromic-substring/description/

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

算法分析

Manacher's Algorithm 马拉车算法

提交代码:

class Solution {
public:
    string longestPalindrome(string s) {
        string str = "$#";
        for (int i = 0; i < s.size(); ++i)
        {
            str += s[i];
            str += '#';
        }
        
        vector<int> p(str.size(), 0);
        int mx = 0, id = 0, resLen = 0, resCenter = 0;
        for (int i = 0; i < str.size(); ++i)
        {
            p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
            
            while(str[i + p[i]] == str[i - p[i]]) ++p[i];
            
            if(mx < i + p[i])
            {
                mx = i + p[i];
                id = i;
            }
            
            if(p[i] > resLen)
            {
                resLen = p[i];
                resCenter = i;
            }
        }
        
        return s.substr((resCenter - resLen) / 2, resLen - 1);
    }
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string str, string expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	string result = s.longestPalindrome(str);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("babad"), string("bab"));
	Test("Test2", string("cbbd"), string("bb"));
	Test("Test3", string("a"), string("a"));

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82386196