×

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy.

The values of (centerRightPosition - currentRightPosition) and LPS length at currentLeftPosition, respectively, determine the four scenarios (R – i). These two pieces of knowledge allow us to utilise previously acquired data without comparing unneeded characters.

Manacher's Algorithm - Longest Palindromic Substring in Linear Time

In each of the four scenarios, we first set the least of L[iMirror] as well as R-i to L[i], and then we attempt to make the palindrome as long as possible.

Given that one is familiar with the LPS size arrays, position, index, symmetry property, and other terms, the above observation might appear more logical, understandable, and simple to apply.

Execution:

// Manacher's Algorithm implementation program in java
import java.util.*;
class Kamal
{
    static void findTheLongestPalindromicString(String message)
    {
        int M = message.length();
        if (M == 0)
            return;
        M = 2 * M + 1; // The position number
        int[] K = new int[M + 1]; // Length of LPS Array
        K[0] = 0;
        K[1] = 1;
        int D = 1; // The Position at center
        int A = 2; // The position of centerRightPosition
        int j = 0; // The position of currentRightPosition
        int iMirror; // The position of currentLeftPosition
        int themaxLPSLength = 0;
        int themaxLPSCenterPosition = 0;
        int begin = -1;
        int end = -1;
        int differ = -1;
        // To output the LPS Length array, remove the comment.
        // printf("%d %d ", K[0], K[1]);
        for (j = 2; j < M; j++)
        {
            // obtain the currentLeftPosition jMirror and 
           //   use it for the currentRightPosition j.
            jMirror = 2 * D - j;
            K[j] = 0;
            differ = A - j;
 
            // If the currentRightPosition j is well 
            // within the centerRightPosition A
            if (differ > 0)
                K[j] = Math.min(K[jMirror], differ);
 
            // Expand palindrome with currentRightPosition j
          //  as the centre. In this case, for odd places, 
          // we compare the characters, and if a match is found, 
          // we increase the LPS Size by one. If even, 
        // we simply increase LPS by one without 
       // conducting a character comparison.
            while (((j + K[j]) + 1 < M && (j - K[j]) > 0) &&
                               (((j + K[j] + 1) % 2 == 0) ||
                         (message.charAt((j + K[j] + 1) / 2) ==
                          message.charAt((j - K[j] - 1) / 2))))
            {
                K[j]++;
            }
 
            if (K[j] > themaxLPSLength) // Track the themaxLPSLength
            {
                themaxLPSLength = K[j];
                themaxLPSCenterPosition = j;
            }
            // If the palindrome is centred at currentRightPosition j
           //  it will extend beyond centerRightPosition A, 
          // and the centerPosition D will be adjusted in 
           // accordance with the expanded palindrome.
            if (j + K[j] > A)
            {
                D = j;
                A = j + K[j];
            }
            // To output the LPS Length array, remove the comment.
            // printf("%d ", K[j]);
        }
 
        begin = (themaxLPSCenterPosition - themaxLPSLength) / 2;
        end = begin + themaxLPSLength - 1;
        System.out.printf("The LPS for string is %h : ", message);
        for (j = begin; j <= end; j++)
            System.out.print(message.charAt(j));
        System.out.println();
    }
 
    // It is the Driver Code
    public static void main(String[] args)
    {
        String message = "abadabadabddcb";
        findTheLongestPalindromicString(message);
 
        message = "babbab";
        findTheLongestPalindromicString(message);
 
        message = "bababab";
        findTheLongestPalindromicString(message);
 
        message = "badabadabadab";
        findTheLongestPalindromicString(message);
 
        message = "forjavaavajfor";
        findTheLongestPalindromicString(message);
 
        message = "dbab";
        findTheLongestPalindromicString(message);
 
        message = "abacegfecaba";
        findTheLongestPalindromicString(message);
 
        message = "abacegfdcbaab";
        findTheLongestPalindromicString(message);
 
        message = "abcdefedcba";
        findTheLongestPalindromicString(message);
    }
}

Output:

The LPS for string is  abacdabadabddab : badabadab
The LPS for string is  babbab : babbab
The LPS for string is  bababab : bababab
The LPS for string is  badabadabadab : badabadabadab
The LPS for string is  forjavaavajfor : javajava
The LPS for string is  dbab : bab
The LPS for string is  abacegfecaba : aba
The LPS for string is  abacegfdcbaab : baab
The LPS for string is  abcdefedcba : abcdefedcba

Time Complexity of program: O(n)
Auxiliary Space of program: O(n)

When comparing characters for expansion in this case, we had to consider even and odd positions differently (because locations themselves do not correspond to any characters in a string).

Making even positions also represent a character is necessary in order to prevent this inconsistent treatment of even and odd situations (Actually, in character comparison, all even spots should reflect the SAME character). Setting a character to all even spots in the given string or making a fresh duplicate of the given string is one approach to accomplish this.


Related Topics

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.