https://leetcode-cn.com/problems/longest-palindromic-substring/
方法一:中心扩散法
class Solution {
public String longestPalindrome(String s) {
if(s.length()<2) return s;
char[] c = s.toCharArray();
int count;
int point;
int maxcount=0;
int maxpoint=0;
int size=0;
int L=c.length;
boolean flagissig=true;
for (int i = 0; i < L; i++) {
point = i;
size = Math.min(i, L - i - 1);
count = 0;
for (int j = 0; j <= size; j++) {
if (c[i - j] == c[i + j]) {
count++;
continue;
} else {
break;
}
}
if (count > maxcount) {
maxcount = count;
maxpoint = point;
}
}
//回文串是偶数的情况再来一次
for (int i = 0; i < L; i++) {
point = i;
size = Math.min(i, L - i - 2);
count = 0;
for (int j = 0; j <= size; j++) {
if (c[i - j] == c[i + j +1]) {
count++;
continue;
} else {
break;
}
}
if (count >= maxcount) {
flagissig=false;
maxcount = count;
maxpoint = point;
}
}
if(flagissig)
return s.substring(maxpoint - maxcount + 1, maxpoint + maxcount);
else
return s.substring(maxpoint - maxcount + 1, maxpoint + maxcount+1);
}
}
方法二:移动窗口法
public class jarvis {
public static void main(String[] args) {
System.out.println(longestPalindrome("sojrsalskjdef"));
}
public static String longestPalindrome(String s) {
String result = null;
char[] chars = s.toCharArray();
for (int i = chars.length; i >= 1; i--) {
//获取所有这个长度的char数组
for (int a = 0; a <= chars.length - i; a++) {
//判断是否是回文
boolean flag = false;
for (int j = 0; j < i / 2; j++) {
if (chars[a + j] == chars[a + i - 1 - j]) {
} else {
flag = true; //不是回文
}
}
if (flag == false) {
result = s.substring(a, a + i);
return result;
}
}
}
return null;
}
}