Leetcode 214. 最短回文串 C++
2020-06-29 04:34
477 查看
Leetcode 214. 最短回文串
题目
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
测试样例
示例 1:
输入: "aacecaaa" 输出: "aaacecaaa"
示例 2:
输入: "abcd" 输出: "dcbabcd"
题解
本问题可以转化为查找最长的回文前缀,然后把剩下的子串反转后加到最前面。我们知道回文串是反转后不变,我们现在找最长回文前缀子串,我们不妨将s反转后与s进行拼接,显然,最长回文前缀就是最长的回文后缀,也就是前缀和后缀相同,这可以联想到KMP算法。同时我们还需要注意一点,为了避免这个回文前缀跨越了s,我们不妨拼接时,用“#”进行连接,这样我们就保证了,前缀和后缀相同的子串就是我们想要找的最长回文前缀。
我们利用KMP算法求出next数组,最长的前后缀相同的长度便是next数组的最后一个值。详细过程见代码
代码
string shortestPalindrome(string s) { string rev = s; reverse(rev.begin(),rev.end()); string new_s = s + "#" + rev; int newlen = new_s.length(); vector<int> next(newlen,0); for(int i=1; i<newlen; i++){ //利用KMP算法求next数组 int t =next[i-1]; while(t > 0 && new_s[t]!=new_s[i]){ t = next[t-1]; } if(new_s[t] == new_s[i]) t++; next[i] = t; } return rev.substr(0,s.length()-next[newlen-1]) + s; }
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
相关文章推荐
- leetcode之路--leetcode 214. 最短回文串(2)
- LeetCode 214. 最短回文串
- Leetcode刷题28-125.验证回文串(C++)
- [LeetCode] Shortest Palindrome 最短回文串
- 【Leetcode】214. Shortest Palindrome 最短回文串
- Leetcode 1177 构建回文串检测 (C++题解)
- Leetcode Shortest Palindrome (最短回文串)
- [LeetCode] 214. Shortest Palindrome 最短回文串
- LeetCode214.最短回文串
- Leetcode刷题32-821.字符的最短距离(C++)
- LeetCode学习(5)Shortest Palindrome(最短回文串)
- [LeetCode] Shortest Palindrome 最短回文串
- leetcode 95. Unique Binary Search Trees II | Java最短代码实现
- 最长回文串:LeetCode:Longest Palindromic Substring
- #LeetCode# #C++# Binary Tree Inorder Traversal
- leetcode_c++:链表:Reorder List(143)
- LeetCode - 119. Pascal's Triangle II - 思路详解 - C++
- [C++]LeetCode: 79 Next Permutation (下一个排列,常见面试题)
- 【LeetCode-229】Majority Element II(C++)
- LeetCode本博客题解索引(C++实现)