|
| 1 | +// Problem: Longest Palindromic Substring |
| 2 | +// Language: Java |
| 3 | +// Description: Finds the longest palindromic substring in a given string. |
| 4 | +// Handles all edge cases (empty string, single character, multiple solutions). |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +public class LongestPalindromicSubstring { |
| 9 | + |
| 10 | + // Method to find the longest palindromic substring |
| 11 | + public static String longestPalindrome(String s) { |
| 12 | + if (s == null || s.length() < 1) return ""; |
| 13 | + |
| 14 | + int start = 0, end = 0; // indices of the longest palindrome |
| 15 | + for (int i = 0; i < s.length(); i++) { |
| 16 | + int len1 = expandAroundCenter(s, i, i); // odd length palindrome |
| 17 | + int len2 = expandAroundCenter(s, i, i + 1); // even length palindrome |
| 18 | + int len = Math.max(len1, len2); |
| 19 | + if (len > end - start) { |
| 20 | + start = i - (len - 1) / 2; |
| 21 | + end = i + len / 2; |
| 22 | + } |
| 23 | + } |
| 24 | + return s.substring(start, end + 1); |
| 25 | + } |
| 26 | + |
| 27 | + // Helper method to expand palindrome around center |
| 28 | + private static int expandAroundCenter(String s, int left, int right) { |
| 29 | + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { |
| 30 | + left--; |
| 31 | + right++; |
| 32 | + } |
| 33 | + return right - left - 1; // length of palindrome |
| 34 | + } |
| 35 | + |
| 36 | + // Main method to take input and display output |
| 37 | + public static void main(String[] args) { |
| 38 | + Scanner sc = new Scanner(System.in); |
| 39 | + System.out.print("Enter a string: "); |
| 40 | + String input = sc.nextLine(); |
| 41 | + |
| 42 | + String result = longestPalindrome(input); |
| 43 | + |
| 44 | + System.out.println("\nLongest Palindromic Substring: " + result); |
| 45 | + System.out.println("Length: " + result.length()); |
| 46 | + |
| 47 | + sc.close(); |
| 48 | + } |
| 49 | +} |
0 commit comments