给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
我个人认为这样的题目并不难,但是今晚不知道是状态不好还是为啥,硬是看了半天没想出好的解决方案,现在冷静下来以看,只要采用中心扩展算法即可解决问题。(虽然我是看了Leetcode题解才做出来的),下面贴代码吧,就当记录一下了
public String longestPalindrome(String s) {
if(s==null||s.length()==0)
return "";
int index = 0;
int a = 0;
int b = 0;
int maxLen = 0;
while (index<s.length()){
int[] ab = judge(s,index);
int[] ab2 = judge2(s,index);
if((ab[1]-ab[0]+1)>(ab2[1]-ab2[0]+1)) {
if ((ab[1] - ab[0] + 1) > maxLen) {
maxLen = ab[1] - ab[0] + 1;
a = ab[0];
b = ab[1];
}
}else {
if ((ab2[1] - ab2[0] + 1) > maxLen) {
maxLen = ab2[1] - ab2[0] + 1;
a = ab2[0];
b = ab2[1];
}
}
index++;
}
return s.substring(a,b+1);
}
private int[] judge(String s,int index){
int a = index;
int b = index;
int[] result = new int[2];
while (a>=0&&b<s.length()){
if(s.charAt(a)!=s.charAt(b)){
break;
}
a--;
b++;
}
result[0] = a+1;
result[1] = b-1;
return result;
}
private int[] judge2(String s,int index){
int a = index;
int b = index+1;
int[] result = new int[2];
while (a>=0&&b<s.length()){
if(s.charAt(a)!=s.charAt(b)){
break;
}
a--;
b++;
}
result[0] = a+1;
result[1] = b-1;
return result;
}