Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc9e48a

Browse files
Merge pull request youngyangyang04#2757 from huanxiangxingyun/master
0005.最长回文子串 Manacher算法C++版本
2 parents 9da3575 + 13a4234 commit fc9e48a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎problems/0005.最长回文子串.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,60 @@ public:
256256
* 时间复杂度:O(n^2)
257257
* 空间复杂度:O(1)
258258

259+
### Manacher 算法
259260

261+
Manacher 算法的关键在于高效利用回文的对称性,通过插入分隔符和维护中心、边界等信息,在线性时间内找到最长回文子串。这种方法避免了重复计算,是处理回文问题的最优解。
262+
263+
```c++
264+
//Manacher 算法
265+
class Solution {
266+
public:
267+
string longestPalindrome(string s) {
268+
// 预处理字符串,在每个字符之间插入 '#'
269+
string t = "#";
270+
for (char c : s) {
271+
t += c; // 添加字符
272+
t += '#';// 添加分隔符
273+
}
274+
int n = t.size();// 新字符串的长度
275+
vector<int> p(n, 0);// p[i] 表示以 t[i] 为中心的回文半径
276+
int center = 0, right = 0;// 当前回文的中心和右边界
277+
278+
279+
// 遍历预处理后的字符串
280+
for (int i = 0; i < n; i++) {
281+
// 如果当前索引在右边界内,利用对称性初始化 p[i]
282+
if (i < right) {
283+
p[i] = min(right - i, p[2 * center - i]);
284+
}
285+
// 尝试扩展回文
286+
while (i - p[i] - 1 >= 0 && i + p[i] + 1 < n && t[i - p[i] - 1] == t[i + p[i] + 1]) {
287+
p[i]++;// 增加回文半径
288+
}
289+
// 如果当前回文扩展超出右边界,更新中心和右边界
290+
if (i + p[i] > right) {
291+
center = i;// 更新中心
292+
right = i + p[i];// 更新右边界
293+
}
294+
}
295+
// 找到最大回文半径和对应的中心
296+
int maxLen = 0, centerIndex = 0;
297+
for (int i = 0; i < n; i++) {
298+
if (p[i] > maxLen) {
299+
maxLen = p[i];// 更新最大回文长度
300+
centerIndex = i;// 更新中心索引
301+
}
302+
}
303+
// 计算原字符串中回文子串的起始位置并返回
304+
return s.substr((centerIndex - maxLen) / 2, maxLen);
305+
}
306+
};
307+
```
308+
309+
310+
311+
* 时间复杂度:O(n)
312+
* 空间复杂度:O(n)
260313

261314
## 其他语言版本
262315

@@ -682,3 +735,4 @@ public class Solution {
682735
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
683736
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
684737
</a>
738+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /