leetcode Longest Palindromic Substring Part II

寻找最长回文子串
本文介绍了一种高效算法来查找给定字符串中的最长回文子串,通过利用回文的对称特性实现O(n)的时间复杂度。文章详细解释了算法的工作原理,并提供了具体的代码实现。

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.

 

There is little to say about the O(n^2) solution. 

The O(n) solution is by virtue of symmetric property. 

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.

 

So the code is :

 

class Solution {
 public:
  string parse(string& s) {
    string res = "^#";
    for (int i = 0; i < s.length(); ++i)
      res += s.substr(i,1) + "#";
    res += "$";
    return res;
  }
  string longestPalindrome(string s) {
    if (s.length() <= 1)
      return s;
    string T = parse(s);
    int n = T.length();
    vector<int> P(n,0);
    int i, j, C = 0, R = 0, ii;
    for (i = 1; i < n - 1; ++i) {
      ii = C*2 - i;
      P[i] = (R - i) > 0 ? min(P[ii], R - i) : 0;
      while (T[i - 1 - P[i]] == T[i + 1 + P[i]])
        ++P[i];
      if (i + P[i] > R){
        R = i + P[i];
        C= i;    
      }
    }
    int max = 0;
    int maxIndex = 1;
    for (i = 1; i < n - 1; ++i) {
      if (P[i] > max) {
        max = P[i];
        maxIndex = i;
      }
    }
    return s.substr( (maxIndex - max - 1 ) / 2,max);
  }
};

Add some explanations where the complexity is O(n), for the step if (i+P[i] > R):

1. If i+P[i] <= R, the while loop will execute only once because of the sysmetric property

2. If i+P[i]>R, P[i] starts from R-i. The updates for R is linear. 

 

 

 

 

【源码免费下载链接】:https://renmaiwang.cn/s/0e6hs 数字信号处理实习实验二离散信号的频谱分析MATLAB本实验旨在掌握离散时间信号的DTFT和DFT的MATLAB实现,熟悉DTFT和DFT之间的关系,了解信号不同变形的DFT与原信号DFT之间的关系,掌握系统函数和频率响应之间的关系。一、DTFT和DFT的概念DTFT(Discrete-Time Fourier Transform)是对离散时间信号进行频谱分析的重要工具,它可以将时域信号转换为频域信号,从而分析信号的频率特性。DFT(Discrete Fourier Transform)是DTFT的一种近似实现形式,它可以将有限长信号转换为频域信号。二、实验目的1. 掌握离散时间信号的DTFT和DFT的MATLAB实现2. 熟悉DTFT和DFT之间的关系3. 了解信号不同变形的DFT与原信号DFT之间的关系4. 掌握系统函数和频率响应之间的关系三、实验内容1. 自定义一个长度为8点的信号,信号幅度值也由自己任意指定,对该信号作DTFT,分别画出幅度谱和相位谱2. 对信号分别做8点、16点、32点DFT,分别与DTFT合并作图并比较DFT与DTFT之间的关系3. 在信号每两个相邻样本之间插入一个零值,扩充为16点序列,作DFT,画出幅度谱和相位谱,并与原序列的DFT进行比较4. 将信号以8为周期扩展,得到长为16的两个周期,作DFT,画出幅度谱和相位谱,并与原序列的DFT进行比较5. 已知离散时间系统差分方程为y(n)-0.5y(n-1)+0.06y(n-2)=x(n)+x(n-1),求出并画出其频率响应6. 求该系统系统函数,并画极零点图,并通过freqz函数求频率响应四、设计流程1. 自定义序列为x=[1,2,3,4,5,8,9,7]2. 使用MATLAB实现DTFT和DFT3. 画出幅度谱和
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值