Example: Longest Palidrome - rFronteddu/general_wiki GitHub Wiki
Solution
To find the longest palindromic substring in a given string s, we can use several approaches. One of the most efficient methods is the "Expand Around Center" technique, which takes advantage of the fact that a palindrome mirrors around its center.
Approach:
- Expand Around Center: For each character in the string, consider it as the center of a palindrome. There are 2n-1 centers for a string of length n (each character and each pair of characters between characters).
- Expand: From each center, expand outwards as long as the characters on both sides are the same.
- Track the Longest Palindrome: Keep track of the longest palindrome found during the expansions.
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
// Odd length palindromes
int len1 = expandAroundCenter(s, i, i);
// Even length palindromes
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1; // Length of the palindrome
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.longestPalindrome("babad")); // Output: "bab" or "aba"
System.out.println(solution.longestPalindrome("cbbd")); // Output: "bb"
}
}