题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
public int getLongestPalindrome (String str) {
if (str.length() <= 1) {
return str.length();
}
int start = 0, maxLen = 1;
for (int index = 0; index < str.length(); index++) {
int left = index - 1, right = index + 1, curLen = 1;
while (left >= 0 && str.charAt(left) == str.charAt(index)) {
left--;
curLen++;
}
while (right < str.length() && str.charAt(right) == str.charAt(index)) {
right++;
curLen++;
}
while (left >= 0 && right < str.length() &&
str.charAt(left) == str.charAt(right)) {
right++;
left--;
curLen += 2;
}
if (curLen > maxLen) {
start = left;
maxLen = curLen;
}
}
return maxLen;
}
}
查看9道真题和解析