[LeetCode] Longest Palindromic Substring

来源:互联网 发布:python的库怎么安装 编辑:程序博客网 时间:2024/06/06 20:31

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

Example:

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

Example:

Input: "cbbd"Output: "bb"


这道题要求的是找到最长的回文子字符串。所谓会问就是类似”aba", "asdfdsa"这样正反都都一样的字符串。

简单的解题方式就是遍历所有的子字符串,找到最大的回文字符串,但是这样做的时间复杂度可以达到O(n^3),这在字符串较长的情况下是难以接受的。

解决这个问题最好的方法应该是采用Manacher's Algorithm,时间复杂度为线性·,这应该是寻找最长回文子字符串的最佳方法。


class Solution {public:string manacher(string str) {int mid = 0, maxRight = 0;int maxRL = 0, maxPos = 0;vector<int> RL;string s = "/";for (int i = 0; i < str.length(); i++) {s += str[i];s += "/";}for (int i = 0; i < s.length(); i++) {RL.push_back(0);}for (int i = 0; i < s.length(); i++) {if (i > maxRight) {if (RL[2 * maxPos - i] > maxRight - i) {RL[i] = maxRight - 1;} else {RL[i] = RL[2 * maxPos - i];}} else {RL[i] = 0;}while (i - RL[i] - 1 >= 0 && i + RL[i] + 1 < s.length() && s[i - RL[i] - 1] == s[i + RL[i] + 1]) {RL[i]++;}if (RL[i] > maxRL) {maxRL = RL[i];maxPos = i;}}string r = s.substr(maxPos - maxRL, 2 * maxRL + 1);return r;}     string longestPalindrome(string s) {        string str = manacher(s);        string result = "";        for (int i = 0; i < str.length(); i++) {        if (str[i] != '/') {        result += str[i];}}return result;    }};





原创粉丝点击