Final answer:
To find the longest palindrome substring in a string, iterate over all possible substrings, check for palindromicity, and keep track of the longest one found, preferring lexicographically smaller ones in case of ties.
Step-by-step explanation:
To find a substring in a string that is the same when read forwards and backwards (a palindrome), one can use a nested loop algorithm. The key is to iterate over each possible starting and ending point in the string, and check if the substring defined by these points is a palindrome. If it is, and if its length is greater than the currently known longest palindrome, keep track of it. If multiple substrings of the same length are found, keep the lexicographically smallest one.
Algorithm :
- Initialize the longest palindrome substring (longestPalindrome) as an empty string.
- Iterate over the string with two nested loops. The outer loop (i) represents the starting point and the inner loop (j) represents the ending point of the substring.
- For each substring (inputStr.substring(i, j)), check whether it is a palindrome and if it is longer than the current longestPalindrome. If both conditions are satisfied, update the longestPalindrome.
- If two substrings of the same length are found, update the longestPalindrome only if the new substring is lexicographically smaller.
- Continue until all possible substrings have been checked.
- Print the longest palindrome substring found.
Here is the example given:
Input: "YABCCBAZ"
Output: "ABCCBA"
Explanation: The given string is "YABCCBAZ", and the longest palindrome substring is "ABCCBA", which is the same when read forwards and backwards.