当前位置:网站首页>力扣(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;
}
};
边栏推荐
猜你喜欢
随机推荐
关于任命韩文弢博士代理NOI科学委员会主席的公告
解决plt.imshow()不显示图片cv2.imshw()不显示图片
Data warehouse buried point system and attribution practice
Example of embedding code for continuous features
pgaudit 的安装使用《postgresql》
JS 预编译
学会可视化大屏布局技巧,让领导都赞不绝口
SSM整合流程
tmp
《21天精通TypeScript-5》类型注解与原始类型
The ORB - SLAM2 extracting feature points
【OpenCV】 - 显示图像API之imshow()对不同位深度(数据类型)的图像的处理方法
酷雷曼上新6大功能,全景营销持续加码
Postman will return to the interface to generate a json file to the local
JS 原型原型链
10 分钟彻底理解 Redis 的持久化和主从复制
Week5
El - tree set using setCheckedNodessetCheckedKeys default check nodes, and a new check through setChecked specified node
剑指offer专项突击版第18天
ViewModel 记录下 +









