描述
对于长度为n的一个字符串A(仅包含数字,大小写英文字母),请设计一个高效算法,计算其中最长回文子串的长度。
数据范围: 1≤n≤1000
要求:空间复杂度 O(1),时间复杂度 O(n^2)
进阶: 空间复杂度 O(n),时间复杂度 O(n)
题目解法:回文子串右两种类型,一种是奇数长度,一种是偶数长度,采用两个循环分别求解,最后取最大值,作为答案返回。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
public int getLongestPalindrome (String A) {
// write code here
int ans=1;
for(int i=0;i<A.length();i++)
{
int temp=1;
int j=i-1;
int l=i+1;
while(j>=0&&l<A.length())
{
if(A.charAt(j)==A.charAt(l)) {
temp+=2;
ans=Math.max(ans,temp);
}
else{
break;
}
j--;
l++;
}
}
for(int i=0;i<A.length();i++)
{
int temp=0;
int j=i;
int l=i+1;
while(j>=0&&l<A.length())
{
if(A.charAt(j)==A.charAt(l)) {
temp+=2;
ans=Math.max(ans,temp);
}
else{
break;
}
j--;
l++;
}
}
return ans;
}
}