[Leetcode]Longest Palindromic Substring

来源:互联网 发布:编程语言使用排行 编辑:程序博客网 时间:2024/05/08 01:37

Longest Palindromic Substring
Total Accepted: 82394 Total Submissions: 381112 Difficulty: Medium

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Subscribe to see which companies asked this question

使用暴力去做算法的时间复杂度肯定是O(n ^2),然后有一种叫做manacher的算法。可以把时间复杂度降到O(n)。详细的资料:戳这里

class Solution {public:    string longestPalindrome(string s) {        int len = s.size();        if(!len)    return "";        string str("$");        for(int i = 0;i <= len - 1;++ i){            str.push_back('#');            str.push_back(s[i]);        }        str.push_back('#');        len = str.size();        int id = 0;        int maxDis = 0;        vector<int> p(len,0);        for(int i = 1;i <= len - 1;++ i){            if(maxDis > i){                p[i] = min(maxDis - i,p[2 * id - i]);            }            for(;str[i - p[i]] == str[i + p[i]];++ p[i])                ;            if(i + p[i] > maxDis){                id = i;                maxDis = i + p[i];            }        }        int maxLen = 0;        int pos = 0;        for(int i = 0;i <= p.size() - 1;++ i){            if(p[i] > maxLen){                maxLen = p[i];                pos = i;            }        }        string res(str.substr(pos - maxLen + 1,maxLen * 2 - 1));        string ans;        for(auto ch : res){            if(ch != '#'){                ans.push_back(ch);            }        }        return ans;    }};
0 0
原创粉丝点击