Leecode no.5 最长回文子串

package leecode;

/**
* 5. 最长回文子串
*
* 给你一个字符串 s,找到 s 中最长的回文子串。
* @author Tang
* @date 2021/12/22
*/
public class LongestPalindrome {

char[] chars;

/**
* 从头到尾每个元素遍历
* 判断以每个元素为中心分别向左右伸展的最大回文数
*
* @param s
* @return
*/
public String longestPalindrome(String s) {
chars = s.toCharArray();

String maxLine = null;
for(int i = 0; i < chars.length; i++) {
String palindrome = maxPalindrome(i);
if(maxLine == null || palindrome.length() > maxLine.length()) {
maxLine = palindrome;
}
}

return maxLine;
}

/**
*
* @param index 中心元素索引
* @return 最大回文数
*/
private String maxPalindrome(int index) {
if(index == 0 || index == chars.length - 1) {
//过一下测试用例bb
if(chars.length == 2 && chars[0] == chars[1]) {
return String.valueOf(chars);
}

return String.valueOf(chars[index]);
}

//单数回文情况
int leftIndex = index - 1;
int rightIndex = index + 1;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(chars[index]);
String line = getMax(stringBuilder, leftIndex, rightIndex);

//双数回文情况 (中心元素和左边元素相同)
if(chars[index] == chars[index-1]) {
leftIndex = index - 1;
rightIndex = index;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder.append(chars[leftIndex]);
stringBuilder.append(chars[rightIndex]);
String leftLine = getMax(stringBuilder2, leftIndex, rightIndex);
line = leftLine.length() > line.length() ? leftLine : line;
}

//双数回文情况 (中心元素和右边元素相同)
if(chars[index] == chars[index+1]) {
leftIndex = index;
rightIndex = index + 1;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder.append(chars[leftIndex]);
stringBuilder.append(chars[rightIndex]);
String leftLine = getMax(stringBuilder2, leftIndex, rightIndex);
line = leftLine.length() > line.length() ? leftLine : line;
}
return line;
}

/**
* 通过两个指针不断向外判断最大的回文数量
*
* @param leftIndex
* @param rightIndex
* @return
*/
private String getMax(StringBuilder line, int leftIndex, int rightIndex) {
while(leftIndex >= 0 && rightIndex < chars.length) {
if(chars[leftIndex] != chars[rightIndex]) {
break;
}
line.insert(0, chars[leftIndex]);
line.append(chars[rightIndex]);
leftIndex--;
rightIndex++;
}
return line.toString();
}

public static void main(String[] args) {
new LongestPalindrome().longestPalindrome("babad");
}
}
posted @ 2021-12-22 14:39  六小扛把子  阅读(25)  评论(0编辑  收藏  举报