手很顺,今天(2021年6月30日)连刷三题
③最长回文子串-腾讯/华为/美团/京东(本文)
题目描述:
对于一个字符串,请设计一个高效算法,计算其中最长回文子串的长度。
给定字符串A以及它的长度n,请返回最长回文子串的长度。
例:
输入:"abc1234321ab",12
返回值:7
(这是牛客网提供的一道题目,想尝试的码友们,可以通过这个链接挑战https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af?tpId=188&&tqId=38608&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking)
(更多博文,欢迎来我的博客学习交流https://blog.csdn.net/have_a_cat)
分析:
“回文串”是一个正读和反读都一样的字符串
那么,就有两种可能:
□aba式
○abba式
思路:
分别以 (2n-1)个位置为回文串中心,计算回文串长度,并返回其中的最大值。
计算回文串长度--□aba式
字符串A
字符串A的长度n
当前回文串中心为A[i] (□aba式),那么回文串长度j初始值为1,回文串左端指针b_left = i -1,回文串右端指针b_right = i+1。
(其中0 <= i < n)
while((b_left >=0)&(b_right < n)&(A[b_left]==A[b_right]))
{
j = j + 2;
b_left--;
b_right++;
}
/*(更多博文,欢迎来我的博客学习交流https://blog.csdn.net/have_a_cat)*/
计算回文串长度--○abba式
字符串A
字符串A的长度n
当前回文串中心为A[i]与A[i+1]间 (○abba式),那么回文串长度j初始值为0,回文串左端指针b_left = i,回文串右端指针b_right = i+1。
(其中0 <= i < n)
while((b_left >=0)&(b_right < n)&(A[b_left]==A[b_right]))
{
j = j + 2;
b_left--;
b_right++;
}
/*(更多博文,欢迎来我的博客学习交流https://blog.csdn.net/have_a_cat)*/
观察发现,上面计算回文串长度的while()部分相同,我们抽取出来写成一个函数
int finds(string A, int b_left, int b_right, int n, int j)
{
while((b_left >=0)&(b_right < n)&(A[b_left]==A[b_right]))
{
j = j + 2;
b_left--;
b_right++;
}
}
C++代码
class Solution {
public:
int finds(string A, int b_left, int b_right, int n, int j){
while((b_left >= 0)&&(b_right < n)){
if(A[b_left]==A[b_right]){
j += 2;
}else{
break;
}
b_left--;
b_right++;
}
return j;
}
/* (更多博文,欢迎来我的博客学习交流https://blog.csdn.net/have_a_cat) */
int getLongestPalindrome(string A, int n) {
// write code here
/* 依次计算回文串的长度 */
int max_num = 1;
int j, b_left, b_right;
for(int i = 0; i < n; i++){/* ①aba型 */
j = 1;
b_left = i - 1;
b_right = i + 1;
j = finds(A, b_left, b_right, n, j);
max_num = max(max_num, j);
}
for(int i = 0; i < n; i++){/* ②abba型 */
j = 0;
b_left = i;
b_right = i + 1;
j = finds(A, b_left, b_right, n, j);
max_num = max(max_num, j);
}
return max_num;
}
};