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. 屌丝就爱尝鲜头——java8再判断

    这节,我们来通过具体的实例来看看Java8的具体用法. 首当其冲,就是lambda用法. 这里的案例,就是用lambda来实现runnable接口,我们知道以前用匿名内部类的方式来实现runnable ...

  2. 【R】函数-数学函数

  3. 解决PHP使用CVS导出Excel乱码问题

    在使用PHP生成CVS文件后通过Excel打开发现中文全部变成了乱码,之前在我本地win08通过WPS正常的,但上传到服务器Linux在服务器上测试出现了乱码 一开始以后是Linux的问题但后来测试时 ...

  4. (转)真正的中国天气api接口xml,json(求加精) ...

      我只想说现在网上那几个api完全坑爹有木有??? 官方的申请不来有木有,还有收费有木有?? 咱这种菜鸟只能用免费的了!!!! http://m.weather.com.cn/data/101110 ...

  5. [Spring boot] Autowired by name, by @Primary or by @Qualifier

    In the example we have currently: @Component public class BinarySearchImpl { @Autowired private Sort ...

  6. 【python】使用py3-bencode打开torrent文件

    没想到这个原始版本访问量超过了后继版本,估计有些流量是搜索引擎带来的,有些人并不会点击左边“我的随笔”去找新的版本. 现把后继版本地址贴一下:http://www.cnblogs.com/xiande ...

  7. APUE 3rd

    以下是APUE 3rd edition 的preface,从04年的第二版到现在的第三版,APUE内容有所更新.点击下载. It’s been almost eight years since I fi ...

  8. uni - 使用npm

    一.使用 1. 在当前根目录初始化package.json npm init -y 2. 安装(自动生成node_modules文件夹) npm i packageName yarn add pack ...

  9. 高级NUMA参数

    Advanced NUMA Attributes You can use the advanced NUMA attributes to customize NUMA usage. Attribute ...

  10. MySql 比Replace Into更适合的用法,外加SqlServer的方式。

    Mysql: INSERT INTO `his_examine_result` (Mid,His_Examine_Mid, His_File_Mid, ResultType, His_Employee ...