5.Longest Palindromic Substring (String; DP, KMP)

本文深入探讨了利用动态规划和KMP算法解决字符串问题中寻找最长回文子串的方法。详细解释了两种算法的核心思想、实现步骤,并通过实例演示了如何高效求解。对于理解字符串匹配与回文性质有极高的参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路I:动态规划,遍历到i的时候要保证之前的元素都已经计算过状态,所以遍历顺序同插入排序,时间复杂度O(n2)

class Solution {
public:
    string longestPalindrome(string s) {
      int len = s.length();
      if(len==0) return s;
      
      bool dp[len][len]={false};
      int maxLen=1;
      int start=0;
      
      //initialize
      for(int i = 0; i < len; i++){
          dp[i][i]=true;
      }
      
      for(int i=1; i<len; i++){
          for(int j = 0; j<i; j++){
              if(s[i]==s[j] && (j==i-1 || dp[j+1][i-1])){
                  dp[j][i]=true;
                  if(i-j+1 > maxLen){
                      maxLen=i-j+1;
                      start=j;
                  }
              }
          }
      }
      
      return s.substr(start, maxLen);
    }
};

 

思路II:KMP,一种字符串匹配方法。

首先在字符串的每个字符间加上#号。For example: S = “abaaba”, T = “#a#b#a#a#b#a#”。这样所有的回文数都是奇数,以便通过i的对应位置i’获得p[i]
P[i]存储以i为中心的最长回文的长度。For example: 
T = # a # b # a # a # b # a #
P = 0 1 0 3 0 1 6 1 0 3 0 1 0
下面我们说明如何计算P[i]。
假设我们已经处理了C位置(中心位置),它的最长回文数是abcbabcba,L指向它左侧位置,R指向它右侧位置。
字符串查找——扩展的KMP问题
现在我们要处理i位置。
p[i]必定>=p[i'],那是因为在L到R范围内,i'的左侧与i的右侧相同,i'的右侧与i的左侧相同,i'左侧与右侧相同 =>i左侧与右侧相同。具体地,
if P[ i' ] ≤ R – i,
then P[ i ] ← P[ i' ]
else P[ i ] ≥ P[ i' ]. (Which we have to expand past the right edge (R) to find P[ i ].
If the palindrome centered at i does expand past R, we update C to i, (the center of this new palindrome), and extend R to the new palindrome’s right edge.
 
时间复杂度分析:
In each step, there are two possibilities. 
  • If P[ i ] ≤ R – i, we set P[ i ] to P[ i' ] which takes exactly one step. 
  • Otherwise we attempt to change the palindrome’s center to i by expanding it starting at the right edge, R. Extending R (the inner while loop) takes at most a total of N steps, and positioning and testing each centers take a total of N steps too. Therefore, this algorithm guarantees to finish in at most 2*N steps, giving a linear time solution.

那么总共时间复杂度最坏是O(n2),最好是O(n)

class Solution {
public:
  string preProcess(string s) {
    int n = s.length();
    if (n == 0) return "^$";
    string ret = "^"; //开始符^
    for (int i = 0; i < n; i++)
      ret += "#" + s.substr(i, 1);
 
    ret += "#$"; //结束符$
    return ret;
  }
 
  string longestPalindrome(string s) {
    string T = preProcess(s);
    int n = T.length();
    int *P = new int[n]; //状态数组长度等于原来字符串的长度,不用给#计算状态
    int C = 0, R = 0;
    for (int i = 1; i < n-1; i++) {
      int i_mirror = 2*C-i; // equals to i_mirror = C - (i-C)
    
      //if p[i_mirror] < R-i: set p[i] to p[i_mirror]
      P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;
    
      //else: Attempt to expand palindrome centered at i
      while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) //因为有哨兵^$所以不用担心越界; +1, -1检查下一个元素是否相等,若相等,扩大p[i]
        P[i]++;
      
      //if the palindrome centered at i does expand past R
      if (i + P[i] > R) {
        C = i;
        R = i + P[i];
      }
    }
 
    // Find the maximum element in P.
    int maxLen = 0;
    int centerIndex = 0;
    for (int i = 1; i < n-1; i++) {
      if (P[i] > maxLen) {
        maxLen = P[i];
        centerIndex = i;
      }
    }
    delete[] P;
  
    return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
  }
};

 

 

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4644554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值