LeetCode -- 5 -- 最长回文子串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba"也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"

std::string longestPalindrome(std::string s) 
{        
    const int len = s.size();
    if(1 >= len) 
        return s;
    if(2 == len && s[0] == s[1]) 
        return s;
    
    std::cout << "size of string : " << len << std::endl;
    
    std::string temp;
    for (int i = 0; i < len; i++)
    {
        temp.push_back('#');
        temp.push_back(s[i]);
    }
    temp.push_back('#');
    temp.push_back('\0');
    
    int max = 0;
    int idx = 0;
    for (int i = 0; i < 2 * len + 1; i++)
    {
        int j = i;
        int z = i;
        int count = 0;

        while ((++z) < (2 * len + 1) && (--j >= 0) && (temp[z] == temp[j]))
        {
            count++;
            if (count > max)
            {
                max = count;
                idx = i;
            }
        }
    }
    return s.substr((idx - max) / 2, max);

猜你喜欢

转载自www.cnblogs.com/fanshuai/p/9248186.html