LeetCode-最长回文子串

确定一个中点朝两边扩散,思路就在代码里了······
提交测试7ms,唯一的疑问就是LeetCode那段4ms的过的代码,为什么比我的快,时间复杂度明明一样。

#include <cstdio>
#include <iostream>

using namespace std;

class Solution {
public:
    string longestPalindrome(string p) {
        p = "&" + p;
        string ss;
        int ans = 1;
        int beg = 1, end = 1;
        for (int i = 1; p[i]; ++i) {
            int b = i, e = i, t;
            while (p[e + 1] == p[i]) ++e;//跳过连续重复的子串
            i = e;
            while (p[b - 1] == p[e + 1]) --b, ++e;//向两边扩散,b和e记录回文子串起终点
            if ((t = e - b + 1) > ans) {
                beg = b, end = e;
                ans = t;
            }
        }
        for (int h = beg; h < end + 1; h++) {
            ss.push_back(p[h]);
        }
        return ss;
    }
};

int main() {
    Solution sf;
    string str = "acasd";
    cout << sf.longestPalindrome(str);

    return 0;
}
点赞