当前位置:网站首页>力扣(LeetCode)214. 打家劫舍 II(2022.08.02)
力扣(LeetCode)214. 打家劫舍 II(2022.08.02)
2022-08-03 06:41:00 【ChaoYue_miku】
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例 1:
输入:s = “aacecaaa”
输出:“aaacecaaa”
示例 2:
输入:s = “abcd”
输出:“dcbabcd”
提示:
0 <= s.length <= 5 * 104
s 仅由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shortest-palindrome
方法一:KMP算法
C++提交内容:
class Solution {
public:
string shortestPalindrome(string s) {
int n = s.size();
vector<int> fail(n, -1);
for (int i = 1; i < n; ++i) {
int j = fail[i - 1];
while (j != -1 && s[j + 1] != s[i]) {
j = fail[j];
}
if (s[j + 1] == s[i]) {
fail[i] = j + 1;
}
}
int best = -1;
for (int i = n - 1; i >= 0; --i) {
while (best != -1 && s[best + 1] != s[i]) {
best = fail[best];
}
if (s[best + 1] == s[i]) {
++best;
}
}
string add = (best == n - 1 ? "" : s.substr(best + 1, n));
reverse(add.begin(), add.end());
return add + s;
}
};
边栏推荐
猜你喜欢
随机推荐
信息学奥赛一本通T1446:素数方阵
How to choose a reliable and formal training institution for the exam in September?
控制bean的加载
【C语言】函数栈帧的创建和销毁详解
postman将接口返回结果生成json文件到本地
jvm 面试题
【图像去雾】基于matlab暗通道和非均值滤波图像去雾【含Matlab源码 2011期】
Example of embedding code for continuous features
华为设备配置BFD单跳检测二层链路
word之图表目录中点号位置提升3磅
学习Glide 常用场景的写法 +
数据仓库指标体系实践
[机缘参悟-59]:《素书》-6-安于礼仪[安礼章第六]
Sqoop 导入导出 Null 存储一致性问题
Week5
MySQL日期和时间戳的转换
升级
【图像去噪】基于matlab稀疏表示KSVD图像去噪【含Matlab源码 2016期】
解决登录vCenter提示“当前网站安全证书不受信任“
Haisi project summary









