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==) return s; bool dp[len][len]={false};
int maxLen=;
int start=; //initialize
for(int i = ; i < len; i++){
dp[i][i]=true;
} for(int i=; i<len; i++){
for(int j = ; j<i; j++){
if(s[i]==s[j] && (j==i- || dp[j+][i-])){
dp[j][i]=true;
if(i-j+ > maxLen){
maxLen=i-j+;
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指向它右侧位置。
现在我们要处理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 == ) return "^$";
string ret = "^"; //开始符^
for (int i = ; i < n; i++)
ret += "#" + s.substr(i, ); ret += "#$"; //结束符$
return ret;
} string longestPalindrome(string s) {
string T = preProcess(s);
int n = T.length();
int *P = new int[n]; //状态数组长度等于原来字符串的长度,不用给#计算状态
int C = , R = ;
for (int i = ; i < n-; i++) {
int i_mirror = *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]) : ; //else: Attempt to expand palindrome centered at i
while (T[i + + P[i]] == T[i - - 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 = ;
int centerIndex = ;
for (int i = ; i < n-; i++) {
if (P[i] > maxLen) {
maxLen = P[i];
centerIndex = i;
}
}
delete[] P; return s.substr((centerIndex - - maxLen)/, maxLen);
}
};

5.Longest Palindromic Substring (String; DP, KMP)的更多相关文章

  1. 5. Longest Palindromic Substring (DP)

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  2. Leetcode:【DP】Longest Palindromic Substring 解题报告

    Longest Palindromic Substring -- HARD 级别 Question SolutionGiven a string S, find the longest palindr ...

  3. 5. Longest Palindromic Substring(最长回文子串 manacher 算法/ DP动态规划)

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  4. *5. Longest Palindromic Substring (dp) previous blogs are helpful

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  5. LeetCode第[5]题(Java):Longest Palindromic Substring 标签:String、动态规划

    题目中文:求最长回文子串 题目难度:Medium 题目内容: Given a string s, find the longest palindromic substring in s. You ma ...

  6. 【LeetCode】Longest Palindromic Substring 解题报告

    DP.KMP什么的都太高大上了.自己想了个朴素的遍历方法. [题目] Given a string S, find the longest palindromic substring in S. Yo ...

  7. [LeetCode] Longest Palindromic Substring 最长回文串

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  8. Leetcode Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  9. 【leedcode】 Longest Palindromic Substring

    Given a , and there exists one unique longest palindromic substring. https://leetcode.com/problems/l ...

随机推荐

  1. 错误:Unsupported major.minor version 51.0(jdk版本错误)

    Java.lang.UnsupportedClassVersionError: org/apache/nutch/crawl/Crawl3 : Unsupported major.minor vers ...

  2. 小甲鱼-005python数据类型

    整型:python3整形理论上没有长度限制,很容易进行大数的运算. 浮点型:没有小数点就是整形,有小数点就是浮点型 e记法:科学技术法1.5e3,即1500,1.3e-4即0.0001.3,e记法是浮 ...

  3. innerHTML与jquery里的html()区别介绍

    我原本一直以为innerHTML和jquery里的html其实是完全一样的,jquery是多此一举了,直到我遇到一次问题   看个示例: 复制代码 代码如下: var tbody=document.c ...

  4. trigger和triggerHandler的使用

    今天琢磨了好久这个trigger和triggerHandler的用法.在网上搜了好多,不过大都是相互抄袭,毛意思都没有.后来自己做了研究. trigger: 1.可以用来触发事件. <input ...

  5. fio与dd测试结果记录

    以下测试基于win7内安装的vbox虚机内进行. vbox-vm挂载了7.2k disk作为本地系统盘,挂载了ssd 8G空间作为mount /mnt/data /dev/sdb 今天顺便了做个一个简 ...

  6. Python入门一:简单得不能再简单了##

    从python的语法上看,简单得不能再简单了. 想学它,请移步廖雪峰python2.7教程以及python3.这实在是最好的入门教程.参考资料太多: 外国的教程 Python 入门指南 Python ...

  7. 基于Redis位图实现用户签到功能

    场景需求 适用场景如签到送积分.签到领取奖励等,大致需求如下: 签到1天送1积分,连续签到2天送2积分,3天送3积分,3天以上均送3积分等. 如果连续签到中断,则重置计数,每月初重置计数. 当月签到满 ...

  8. linux系统下修改文件夹目录权限-chmod

    Linux.Fedora.Ubuntu修改文件.文件夹权限的方法差不多.很多人开始接触Linux时都很头痛Linux的文件权限问题.这里告诉大家如何修改Linux文件-文件夹权限.以主文件夹下的一个名 ...

  9. uva-167-枚举

    题意:八皇后问题,要求选取的总和最大 #include<stdio.h> #include<iostream> #include<sstream> #include ...

  10. 24. (ora-01410无效的rowid)临时表 on commit delete rows 与 on commit preserve rows 的区别

    ora-01410无效的rowid解决方式: 把临时表空间改成会话级别的就可以了,即把临时表的创建选项由on commit delete rows改为on commit preserve rows,就 ...