Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
class Solution {
public String longestPalindrome(String s) {
char[] ch = s.toCharArray();
int left = 0, right = 0;
int max = 0;
for (int i = 0; i < ch.length; i++) {
if (judge(ch, i-max-1, i)) {
left=i-max-1; right = i;
max += 2;
}else if(judge(ch, i-max, i)) {
left=i-max; right = i;
max += 1;
}
}
return s.substring(left, right+1);
}
public static boolean judge(char[] ch, int l, int r) {
if (l < 0)
return false;
while (l < r) {
if (ch[l++] != ch[r--])
return false;
}
return true;
}
}
本文介绍了一种高效算法来找出给定字符串中的最长回文子串。通过判断中心扩展的方法,该算法能够处理最大长度为1000的字符串,并提供详细的实现步骤和示例。
817

被折叠的 条评论
为什么被折叠?



