×

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

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.