leetcode第五题 寻找最长的回文子串
中心扩散法
class Solution {
public String longestPalindrome(String s) {
if (s.length() == 0) {
return "";
}
int strLen = s.length();
int left = 0;
int right = 0;
int len = 1;
//用这个来对最大的长度进行统计,因为每一个都会进行对了呢进行重置
int maxLen = 0;
//记录开始的位置,并且定时进行刷新
int maxStart = 0;
for (int i = 0; i < strLen; i++) {
left = i - 1;
right = i + 1;
while (left >= 0 && s.charAt(left) == s.charAt(i)) {
left--;
len++;
}
while (right < strLen && s.charAt(right) == s.charAt(i)) {
right++;
len++;
}
while (left >= 0 && right < strLen && s.charAt(left) == s.charAt(right)) {
len += 2;
right++;
left--;
}
if (len > maxLen) {
maxLen = len;
maxStart = left;
}
len = 1;
}
//对返回的子串进行分割
return s.substring(maxStart+1,maxStart + maxLen + 1);
}
}
动态规划
使用二维数组进行记录
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
int maxEnd = 0;
int maxLen = 0;
int[][] arr = new int[len][len];
String reverse = new StringBuffer(s).reverse().toString();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (s.charAt(i) == reverse.charAt(j)){
if (i == 0 || j == 0) {
arr[i][j] = 1;
}else{
arr[i][j] = arr[i - 1][j - 1] + 1;
}
}
if (arr[i][j] > maxLen) {
int beforeRev = len - 1 - j;
if (beforeRev + arr[i][j] - 1 == i) { //判断下标是否对应
maxLen = arr[i][j];
maxEnd = i;
}
}
}
}
return s.substring(maxEnd - maxLen + 1,maxEnd + 1);
}
}