Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.

这题比较直观的解法是,寻找s中以s[0]为起始的最长回文子串pres(因此是从s的尾部往前遍历,判断是回文即返回),

即后续部分为sufs,然后只需要在s之前补全reverse_sufs的逆转即可。

这样的话reverse_sufs与sufs对称,pres自己与自己对称,肯定是最短回文串。

最坏复杂度为O(n^2),n为s中字符个数。

然而被某个奇葩的测试用例超时了。

先贴出来吧,个人认为面试的十分钟内能写出这个已经可以pass了。

后文再贴标准做法。

class Solution {
public:
string shortestPalindrome(string s) {
if(s == "")
return s;
int i = s.size()-;
while(i >= )
{
// spre is s[0,...,i]
string spre = s.substr(, i+);
if(isPalin(spre))
break;
i --;
}
string pre = s.substr(i+);
reverse(pre.begin(), pre.end());
return pre + s;
}
bool isPalin(string s)
{
for(int i = , j = s.size()-; i < j; i ++, j --)
{
if(s[i] != s[j])
return false;
}
return true;
}
};

首先确认一点基本知识,如果某个字符串str是回文的,那么str == reverse(str)

因此,将s逆转之后拼接在s后面,即news=s+reverse(s),该新字符串news首尾相同的部分,即为s中以s[0]为起始的最长回文子串pres

只不过这里我不用上述的遍历来做,而用类似KMP算法求next数组来做。

在KMP算法中求next数组就是s自我匹配的过程,next[i]的值就表示s[i]之前有几个元素是与s开头元素相同的。

因此,next[news.size()]的值就表示news中首尾相同的部分的长度。接下来就好做了。

注意:当next[news.size()]的值大于s.size()时,说明重复部分贯穿了s与reverse(s),应该修正为next[news.size()]+1-s.size()

class Solution {
public:
string shortestPalindrome(string s) {
if(s == "")
return s;
string s2 = s;
reverse(s2.begin(), s2.end());
string news = s + s2;
int n = news.size();
vector<int> next(n+);
buildNext(news, next, n);
if(next[n] > s.size())
next[n] = next[n] + - s.size();
string pres = s.substr(next[n]);
reverse(pres.begin(), pres.end());
return pres + s;
}
void buildNext(string& s, vector<int>& next, int n)
{
int k = -;
int j = ;
next[] = -;
while(j < n)
{
if(k == - || s[j] == s[k])
{
k ++;
j ++;
next[j] = k;
}
else
{
k = next[k];
}
}
}
};

【LeetCode】214. Shortest Palindrome的更多相关文章

  1. 【LeetCode】214. Shortest Palindrome 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 前缀是否回文 判断前缀 相似题目 参考资料 日期 题 ...

  2. 【LeetCode】9、Palindrome Number(回文数)

    题目等级:Easy 题目描述: Determine whether an integer is a palindrome. An integer is a palindrome when it rea ...

  3. 【LeetCode】680. Valid Palindrome II

    Difficulty:easy  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/valid-palindrome ...

  4. 【LeetCode】409. Longest Palindrome 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:字典统计次数 方法二:HashSet 方法三 ...

  5. 【LeetCode】862. Shortest Subarray with Sum at Least K 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 队列 日期 题目地址:https://leetcod ...

  6. 【LeetCode】847. Shortest Path Visiting All Nodes 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/shortest ...

  7. 【LeetCode】581. Shortest Unsorted Continuous Subarray 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 方法一:排序比较 日期 题目地址:https://leetco ...

  8. 【LeetCode】125. Valid Palindrome 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 列表生成式 正则表达式 双指针 日期 题目地址:https:/ ...

  9. 【LeetCode】680. Valid Palindrome II 验证回文字符串 Ⅱ(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 思路来源 初版方案 进阶方案 日期 题目地址 ...

随机推荐

  1. 计算GDOP

    #include <iostream> #include <fstream> #include "..\include\CPosition.h" #incl ...

  2. 深挖android low memory killer

    对于PC来说,内存是至关重要.如果某个程序发生了内存泄漏,那么一般情况下系统就会将其进程Kill掉.Linux中使用一种名称为OOM(Out Of Memory,内存不足)的机制来完成这个任务,该机制 ...

  3. 详解管理root用户权限的sudo服务程序

    在你想要使用超级权限临时运行一条命令时,sudo 命令非常方便,但是当它不能如你期望的工作时,你也会遇到一些麻烦.比如说你想在某些日志文件结尾添加一些重要的信息,你可能会尝试这样做: $ echo & ...

  4. Spring(十四):使用FactoryBean配置Bean

    FactoryBean简介: 1)Spring中Bean包含两种一种是普通Bean,另外一种是FactoryBean.它们都受IOC容器管理,但是也有不同之处. 2)普通Bean与FactoryBea ...

  5. C#.NET常见问题(FAQ)-如何在不同窗体之间传递值

    最简单的方法是在定义窗体的时候就写好几个变量,在实例化Form2的时候,就把这些参数传递过去   或者你也可以定义一个类,然后通过这个类的静态变量交互(注意只能用静态的,因为Form2无法访问Form ...

  6. C语言处理文件

    C写入数据到文件 #include <stdio.h> #include <string.h> int main( ) { FILE* fd = fopen("txt ...

  7. STL 笔记(四) 迭代器 iterator

    stl 中迭代器能够理解为面向对象版本号的广义指针,提供了对容器中的对象的訪问方法,能够遍历容器全部元素.也能够訪问随意元素.stl 迭代器有下面五种: Input iterators   仅仅读,输 ...

  8. 【树莓派】树莓派上刷android系统

    这位前辈之前做了基于android2.3版本刷入树莓派的事情,http://blog.csdn.net/lichwei1983/article/details/44082669 1.android 镜 ...

  9. linux2.6.30.4内核移植(4)——完善串口驱动

    在内核里支持两个串口,也就是芯片的UART0和UART1,而UART2的驱动是针对红外接口的,而不是串口驱动,这里将其修改为串口驱动. 一.修改内核源码arch/arm/mach-s3c2440/ma ...

  10. React (native) 相关知识

    container component provider组件 react里的redux进阶玩法 react组件的生命周期 conductor / componentWillMount / render ...