// Java program to implement manachar's alogirthm import java.util.; class GfG { static…
- User
// Java program to implement manachar's alogirthm import java.util.*;
class GfG { static void findLongestPalindromicString(String text) { int N = text.length(); if (N == 0) return;
// Transform the original string length N = 2 * N + 1; // LPS Length Array int[] L = new int[N]; L[0] = 0; L[1] = 1; // Initialize center and right boundary int C = 1; int R = 2; // Initialize max LPS based on the first character int maxLPSLength = L[1]; int maxLPSCenterPosition = 1; int i, iMirror; int expand = -1; int diff = -1; int start = -1; int end = -1; for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no expansion required expand = 0; diff = R - i; // If currentRightPosition i is within centerRightPosition R if (diff >= 0) { if (L[iMirror] < diff) { L[i] = L[iMirror]; } else if (L[iMirror] == diff && R == N - 1) { L[i] = L[iMirror]; } else if (L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; expand = 1; } else if (L[iMirror] > diff) { L[i] = diff; expand = 1; } } else { L[i] = 0; expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered at currentRightPosition i while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } } // Track maxLPSLength if (L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i expands beyond R, adjust centerPosition C based on expanded palindrome if (i + L[i] > R) { C = i; R = i + L[i]; } } // Calculate start and end indices in the original string start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; for (i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println(); } public static void main(String[] args) { String text1 = "babcbabcbaccba"; findLongestPalindromicString(text1); }} Hangup (SIGHUP) Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at GfG.findLongestPalindromicString(GfG.java:66) at GfG.main(GfG.java:95) Remove this error
- Assistant