题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return int整型
*/
public int getLongestPalindrome (String str) {
if (str.isEmpty()) {
return 0;
}
char[] chars = str.toCharArray();
int maxLen = 1;
for (int i = 0; i < chars.length; i++) {
int max = Math.max(helper(chars, i, i), helper(chars, i, i + 1));
//维护最大长度
maxLen = Math.max(maxLen, max);
}
return maxLen;
}
/**
* 返回以left和 right为中心点的回文字串的长度
* @param chars
* @param left
* @param right
* @return
*/
public static int helper(char[] chars, int left, int right) {
while (left >= 0 && right < chars.length && chars[left] == chars[right]) {
left --;
right ++;
}
return right - left + 1 - 2;
}
}
#刷题记录##刷题#
上海得物信息集团有限公司公司福利 1166人发布
