LeetCode - Shortest Palindrome (KMP)
来源:互联网 发布:女式凉鞋淘宝网 编辑:程序博客网 时间:2024/05/07 10:58
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"
.
思路:主要是要看从字符串的最左侧起的最长回文串是什么,可以借助kmp中最长公共前缀后缀的计算方法来计算
class Solution {public: string shortestPalindrome(string s) { string r = s; reverse(r.begin(), r.end()); string t = s + "#" + r; int l = t.length(); vector<int> p(l, 0); for(int i = 1; i < l; ++i){ int j = p[i - 1]; while(j > 0 && t[j] != t[i]) j = p[j - 1]; p[i] = j + (t[j] == t[i]); } return r.substr(0, r.size() - p[l - 1]) + s; }};
0 0
- LeetCode - Shortest Palindrome (KMP)
- LeetCode Shortest Palindrome(kmp的妙用)
- LeetCode 214 Shortest Palindrome (KMP next数组)
- Shortest Palindrome(KMP)
- 214. Shortest Palindrome(KMP)
- leetcode 214. Shortest Palindrome 最短回文数 + KMP算法
- leetcode 214: Shortest Palindrome
- leetcode - Shortest Palindrome
- LeetCode Shortest Palindrome
- 【回文】leetcode - Shortest Palindrome
- Shortest Palindrome Leetcode Java
- Shortest Palindrome leetcode-java
- [LeetCode] Shortest Palindrome I
- LeetCode #214 Shortest Palindrome
- [leetcode] 214.Shortest Palindrome
- Shortest Palindrome -- leetcode
- LeetCode 214. Shortest Palindrome
- leetcode 214: Shortest Palindrome
- LeetCode - Merge Intervals
- 脏读、不可重复读和虚读
- iOS之@selector的函数传递多个参数
- jQuery解决引用多个JavaScript库引起的$命名冲突的问题
- 数据库基础知识
- LeetCode - Shortest Palindrome (KMP)
- ssh协议是什么,有什么优点?
- 编程之美读书笔记_3.8 求二叉树中节点的最大距离
- 网络号与主机号的计算以及子网的划分
- HDU Reward(发工资) 2647 (拓扑排序 vector)
- Mongodb-使用C#Drivers实现增删改查
- C # 和 Java的不同之处
- php header解决乱码问题及其他乱码问题
- Jquery 实现表单验证,所有验证通过方可提交