package com.demo; public class TestSubPalindrome { /** * * @param s * @param left * @param right * @return */ static public String helper(String s, int
left, int right) { if (left > right) return null; if(left >= 0 && right <
s.length() && s.charAt(left) == s.charAt(right)) return helper(s,left-1,right+1); else return s.substring(left + 1, right); } /** * * @param s * @return */ public static String longestPalindrome(String
s) { if (s == null) return null; String longest = s.substring(0, 1); for (int i = 0; i < s.length() - 1; i++)
{ //odd cases like 121 String palindrome = helper(s, i, i); if (palindrome.length() >
longest.length()) { longest = palindrome; } //even cases like 1221 palindrome = helper(s, i, i + 1); if (palindrome.length() >
longest.length()) { longest = palindrome; } } return longest; } public static void main(String args[]) { String str = "ABCCBAKARTIKMANDALOLADNAMKITRAKOJMALABCDCBA"; // String str = "MOMABCCBAKA"; System.out.println("Print longest palindrome from the word " + longestPalindrome (str)); } } |
java
Longest
palindromic substring is: MALABCDCBA |
The Java code you provided is designed to find the longest
palindromic substring within a given string. Let's break down the code and how
it works:
Explanation of the Code:
- helper(String
s, int left, int right):
- This
is a recursive helper method that expands around a potential center of a
palindrome.
- It
checks characters on the left and right of a given center (or centers for
even-length palindromes).
- If
the characters match, it continues expanding outward, and when they stop
matching, it returns the palindromic substring.
- longestPalindrome(String
s):
- This
method iterates through each character in the string, treating each
character (and each pair of adjacent characters) as the potential center
of a palindrome.
- It
calls the helper method to expand around the center and find the longest
palindrome for each potential center.
- It
keeps track of the longest palindrome found.
- main(String[]
args):
- The main
method is the entry point of the program.
- It
defines a test string str, which is passed to the longestPalindrome method.
- The
longest palindromic substring found is printed.
Example Output:
For the input string "ABCCBAKARTIKMANDALOLADNAMKITRAKOJMALABCDCBA",
the code will find the longest palindromic substring and print it.
Sub Longest palindrome |
0 Comments