@@ -21,4 +21,67 @@ Given a string `s`, return _the longest_ _palindromic_ **substring** in `s`.
2121** Constraints:**
2222
2323* ` 1 <= s.length <= 1000 `
24- * ` s ` consist of only digits and English letters.
24+ * ` s ` consist of only digits and English letters.
25+
26+ To solve the Longest Palindromic Substring problem in Java using a ` Solution ` class, we'll follow these steps:
27+
28+ 1 . Define a ` Solution ` class with a method named ` longestPalindrome ` .
29+ 2 . Initialize variables to keep track of the start and end indices of the longest palindromic substring found so far (` start ` and ` end ` ).
30+ 3 . Iterate through the string ` s ` :
31+ - For each character in the string, expand around it to check if it forms a palindrome.
32+ - Handle both odd-length and even-length palindromes separately.
33+ - Update ` start ` and ` end ` indices if a longer palindrome is found.
34+ 4 . Return the substring from ` start ` to ` end ` .
35+ 5 . Handle edge cases where the input string is empty or has a length of 1.
36+
37+ Here's the implementation:
38+
39+ ``` java
40+ public class Solution {
41+
42+ public String longestPalindrome (String s ) {
43+ if (s == null || s. length() < 1 ) return " " ;
44+ int start = 0 ;
45+ int end = 0 ;
46+
47+ for (int i = 0 ; i < s. length(); i++ ) {
48+ int len1 = expandAroundCenter(s, i, i);
49+ int len2 = expandAroundCenter(s, i, i + 1 );
50+ int len = Math . max(len1, len2);
51+ if (len > end - start) {
52+ start = i - (len - 1 ) / 2 ;
53+ end = i + len / 2 ;
54+ }
55+ }
56+
57+ return s. substring(start, end + 1 );
58+ }
59+
60+ private int expandAroundCenter (String s , int left , int right ) {
61+ while (left >= 0 && right < s. length() && s. charAt(left) == s. charAt(right)) {
62+ left-- ;
63+ right++ ;
64+ }
65+ return right - left - 1 ;
66+ }
67+
68+ public static void main (String [] args ) {
69+ Solution solution = new Solution ();
70+
71+ // Test cases
72+ String s1 = " babad" ;
73+ System . out. println(" Example 1 Output: " + solution. longestPalindrome(s1));
74+
75+ String s2 = " cbbd" ;
76+ System . out. println(" Example 2 Output: " + solution. longestPalindrome(s2));
77+
78+ String s3 = " a" ;
79+ System . out. println(" Example 3 Output: " + solution. longestPalindrome(s3));
80+
81+ String s4 = " ac" ;
82+ System . out. println(" Example 4 Output: " + solution. longestPalindrome(s4));
83+ }
84+ }
85+ ```
86+
87+ This implementation provides a solution to the Longest Palindromic Substring problem in Java.
0 commit comments