从Shortest Palindrome谈到Manacher和KMP算法
来源:互联网 发布:诸暨行知小学 编辑:程序博客网 时间:2024/05/04 03:50
投出去的三份实习简历都没收到消息...略郁闷...只好闷头刷题了QAQ....
最近按题目类型在重刷Leetcode, 当中做到Shortest Palindrome,开始是用后缀数组做,结果TLE...
只好用马拉车法AC...顺便用KMP算法写了一份AC代码....
后缀数组方法就不说了,可以参考博文后缀数组学习笔记...
马拉车法(Manacher)可以参考博文Manacher算法...下面只贴出Manacher方法AC代码
class Solution{int longestPdr(vector<char> & vc){vector<int> mana(vc.size(), 0);int maxi = -1, maxl = 0, len = 0;for (int i = 0; i < vc.size(); ++i){if (i > maxi + maxl)for (int j = 1; i - j >= 0 && i + j < vc.size() && vc[i - j] == vc[i + j]; mana[i] = j++);else if (mana[2 * maxi - i] == maxi + maxl - i)for (int j = mana[2 * maxi - i]; i - j >= 0 && i + j < vc.size() && vc[i - j] == vc[i + j]; mana[i] = j++);elsemana[i] = mana[2 * maxi - i];if (i + mana[i] > maxi + maxl)maxi = i, maxl = mana[i];}for (int i = 0; i < mana.size(); ++i)if (mana[i] == i)len = i;return len;}public:string shortestPalindrome(string s) {vector<char> vc;for (int i = 0; i < s.length(); ++i){vc.push_back('#');vc.push_back(s[i]);}vc.push_back('#');int maxLen = longestPdr(vc);string str = s.substr(maxLen);for (int i = 0; i < str.length(); ++i){s.insert(0, 1, str[i]);}return s;}};
oK...下面重点说下使用KMP算法...
言语讲不明白...还是贴代码吧...鄙人好懒...
class Solution {vector<int> nextArray(string & s){vector<int> nextA(s.length(), 0);if (s.length() < 3) return nextA;int i = 1, j = 1, k = nextA[1];while (i < s.length() - 1){if (j == 0 || s[i] == s[k]){nextA[++i] = (j == 0 ? 0 : nextA[j] + 1);j = i;k = nextA[j];}else{j = k;k = nextA[j];}}return nextA;}int KMP(string Str, string Pat){vector<int> nextA = nextArray(Pat);int i, j;for (i = 0, j = 0; i < Str.length(); ++i){if (Str[i] == Pat[j]){++j;}else{while (j != 0){j = nextA[j];if (Str[i] == Pat[j]){++j;break;}}}}return j;}public:string shortestPalindrome(string s) {string rs;for (int i = s.length() - 1; i >= 0; --i) rs.push_back(s[i]);int len = KMP(rs, s);string str = s.substr(len);for (int i = 0; i < str.length(); ++i){s.insert(0, 1, str[i]);}return s;}};
0 0
- 从Shortest Palindrome谈到Manacher和KMP算法
- Shortest Palindrome ---再见回文和KMP
- Shortest Palindrome(KMP)
- LeetCode - Shortest Palindrome (KMP)
- 214. Shortest Palindrome(KMP)
- leetcode 214. Shortest Palindrome 最短回文数 + KMP算法
- POJ3974 Palindrome (manacher算法)
- Palindrome Centers Manacher算法
- Manacher算法、KMP算法
- 【算法】(扩展)KMP+manacher
- LeetCode Shortest Palindrome(kmp的妙用)
- LeetCode 214 Shortest Palindrome (KMP next数组)
- leetcode 214:Shortest Palindrome 题目分析 与使用KMP算法的java实现
- POJ:3974 Palindrome (Manacher算法)
- 【manacher算法】POJ 3974 Palindrome
- POJ 3974 Palindrome (Manacher算法)
- POJ 3974-Palindrome(Manacher算法)
- POJ3974 Palindrome(Manacher算法)
- 类的继承
- The type java.util.Map$Entry cannot be resolved.
- 创建快捷图标
- IT成长
- Java虚拟机结构(一)
- 从Shortest Palindrome谈到Manacher和KMP算法
- 配置文件简单使用
- Jstl之核心标签库与格式标签库使用
- 从C语言角度看OC编程里类、类对象
- ZooKeeper多种方式安装
- Android学习笔记
- 项目管理实践教程一、工欲善其事,必先利其器【Basic Tools】
- 黑马程序员——oc和c的差异
- mysql cluster管理节点启动报错