牛客网刷题(五) 寻找回文串(马拉车算法)

 

题目:设计一个算法,寻找字符串中的最长回文子串。

输入一行:一个字符串

输出两行:最长回文子串的长度(无则输出0)

最长回文子串(无则输出空行)

思路:

一个回文串它的对称中心可能是某个字符(aba),也可能是某两个字符之间(aa),理论上我们应该分类讨论?但实际上我们这样操作,我们把字符串变成这样(#a#b#)(#a#b#a#)

这样一来,无论是什么字符串,它的长度都是奇数,只需要一种枚举方式就可以了(奇数的枚举方式,但同时可以枚举的偶数的情况) 

#include<iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;

int fun6(string str)
{
    string tmp;
    int count = 0;
    int maxCount = 0;
    int j = 0;
    string::iterator it = str.begin();
    while (it != str.end())
    {
        tmp.insert(tmp.end(),'#');
        tmp.insert(tmp.end(), *it);
        it++;
    }
    tmp.insert(tmp.end(), '#');
    tmp.insert(tmp.end(), '\0');
    cout << tmp << endl;
    for (int i = 1; i < tmp.size(); i++)
    {
        while (i - count - 1 >= 0 && i + count + 1 < tmp.size() 
                 && tmp[i - count - 1] == tmp[i + count + 1])    
        //枚举对称轴,有对称轴向左右两边枚举
        {
            count++;
        }
        if (count > maxCount)
        {
            maxCount = count;
            j = i;
        }
        count = 0;
    }
    cout << j << endl;
    char *p = &(tmp[j - maxCount]);
    cout << p << endl;
    return maxCount;
}
int main()
{
    string str = "qwqertre";
    int maxCount = fun6(str);
    cout << maxCount << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42736024/article/details/84192066