找出给出的字符串S中最长的回文子串。假设S的最大长度为1000,并且只存在唯一解。
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
/*思路:
从前遍历每个字符,然后把这个字符再从后往前遍历,
如果两个索引一样,则说明不可能回文串中不包含这个字符,则继续从前往后遍历下一个字符
如果两个索引不一样,则可能是回文串得两端,左索引++,右索引--,比较当前字符是否相等,如果不等则放弃,如果相等则知道左右索引相等或相差1结束,计算总的长度,保留最长得一段回文串的左右索引。
*/
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return string字符串
*/
public String longestPalindrome (String s) {
// write code here
if(s.length() < 1 || s == ""){
return null;
}else if(s.length() == 1){
return s;
}else{
int outl = 0;
int outr = 0;
for(int i = 0;i < s.length();i++){
char c = s.charAt(i);
int index = s.lastIndexOf(c);
if(index == i){
continue;
}else{
int l = i;
int r = index;
while(l <= r && s.charAt(l) == s.charAt(r)){
l++;
r--;
}
if(r-l <=1 && (outr-outl) < (index-i)){
outl = i;
outr = index;
}
}
}
return s.substring(outl,outr+1);
}
}
}
京公网安备 11010502036488号