当前位置:网站首页>力扣(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;
}
};
边栏推荐
猜你喜欢
调用feign报错openfeign/feign-core/10.4.0/feign-core-10.4.0.jar
Multi-Head-Attention principle and code implementation
关于NOI 2022的报到通知
一文搞懂什么是@Component和@Bean注解以及如何使用
torch.nn.modules.activation.ReLU is not a Module subclass
RHCSA第四天
PostMan使用,访问路径@RequestMapping
QT信号与槽
How to choose a reliable and formal training institution for the exam in September?
Example of embedding code for continuous features
随机推荐
关于NOI 2022福建省选及省队组成的公告
MYSQL存储过程注释详解
分布式数据库数据一致性的原理、与技术实现方案
信息学奥赛一本通T1452:Keyboarding
学会可视化大屏布局技巧,让领导都赞不绝口
VR全景市场拓展技巧之“拓客宝典”
伦敦银现货市场如何使用多条均线?
Oracle Rac 集群文件目录迁移
STL-vector容器
consul理解
【云原生--Kubernetes】Pod重启策略
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】
excel高级绘图技巧100讲(二十一)- Excel层叠柱形图
hashSet解析
CISP-PTE Zhenti Demonstration
解决plt.imshow()不显示图片cv2.imshw()不显示图片
第六章:存储系统
数据库表结构文档 生成工具screw的使用
postman将接口返回结果生成json文件到本地
计算机网络常见面试题总结