LeetCode(5) - Longest Palindromic Substring

来源:互联网 发布:99是什么意思网络语言 编辑:程序博客网 时间:2024/06/07 17:46

题目描述:

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.

分析:本题可采用三种方法

1)暴力搜索(O(N^3))

2) 动态规划(O(N^2)

P(i,i) is true ;and if s[i]=s[s+1],P(i,i+1) is true

P(i,j)= P(i+1,j-1) ; if s[i]=s[j]

3) 用Manacher's ALGORITHM可达到 O(n) 时间.


方法一:动态规划

class Solution {public:    string longestPalindrome(string s) {        int n = s.length();        int longestBegin = 0;        int maxLen = 1;        bool table[1000][1000] = { false };                for(int i = 0; i < n; i++){            table[i][i] = true;        }                for(int i = 0; i < n-1; i++){            if(s[i] == s[i+1]){                table[i][i+1] = true;                longestBegin = i;                maxLen = 2;            }        }                for(int len = 3; len <= n; len++){            for(int i = 0; i < n-len+1; i++){                int j = i+len-1;                if(s[i] == s[j] && table[i+1][j-1]){                    table[i][j] = true;                    longestBegin = i;                    maxLen = len;                }            }        }        return s.substr(longestBegin, maxLen);    }};

该方法时间复杂度和空间复杂度都为O(N^2),从子串中心求解,可以将空间复杂度降低为O(1)


方法二:

string expandAroundCenter(string s, int c1, int c2) {  int l = c1, r = c2;  int n = s.length();  while (l >= 0 && r <= n-1 && s[l] == s[r]) {    l--;    r++;  }  return s.substr(l+1, r-l-1);} string longestPalindromeSimple(string s) {  int n = s.length();  if (n == 0) return "";  string longest = s.substr(0, 1);  // a single char itself is a palindrome  for (int i = 0; i < n-1; i++) {    string p1 = expandAroundCenter(s, i, i);    if (p1.length() > longest.length())      longest = p1;     string p2 = expandAroundCenter(s, i, i+1);    if (p2.length() > longest.length())      longest = p2;  }  return longest;}

方法三:Manacher's ALGORITHM

class Solution {public:    string longestPalindrome(string s) {        int P[10000];        string t = "$";        for( int i = 0; s[i] != '\0'; i++){            t += "#" + s.substr( i, 1);        }        t += "#";                memset( P, 0, sizeof(P));        int mx = 0, id = 0, mmax = 0;        int len = t.length();        int right = 0;                if(s.length() == 0) return "$";                for(int i = 1; i < len; i++){            P[i] = mx > i ? min(P[2*id-i], mx-i) : 1;            while(t[i + P[i]] == t[i -P[i]]) {                P[i]++;            }            if( i + P[i] > mx){                mx = i + P[i];                id = i;            }            if( mmax < P[i]){                mmax = P[i];                right = i;            }        }                return s.substr(right/2-mmax/2, mmax-1);    }};



参考文章:

[1]LeetCode Online Portal

[2]github LeetCode 

[3]

0 0
原创粉丝点击