Write a java program to find the length of longest prefix in a string which is also a suffix.

Java program to find the prefix and suffix in a string and Java code to Find the longest prefix in the string. In this tutorial let’s see how to find the length of the longest prefix in a string which is also a suffix.

Example:

Input:

Enter a string:

abcab

Output:

The length of the longest suffix and prefix is: 2

Explanation:

abcab

Here, “ab” is the maximum length which is also a suffix. The length is thus 2.

Algorithm to find the length of the longest prefix in a string which is also a suffix

  1. First, take a string input from the user.
  2. The maximum length of the prefix in a string which is also a suffix can be the length of the string divided by 2. And the minimum length can be 0.
  3. Thus, we will create a for loop which runs from i=n/2 to i=0. We will initialize a boolean flag variable to true. It denotes whether we have found our result or not.
  4. Next, we will create another for loop which works on two variables j and k simultaneously. The j variable runs from j=0 to j=i increasing by 1 each time. And the k variable runs from k=i+1 to k=n-1 increasing by 1 each time.
  5. If the character at index j is not found to be equals to the character at index k, we will break the inner for loop and set the boolean flag variable to false (indicating that we have not arrived at the result yet).
  6. Once, the inner for loop is completed with no break statement, it means that for this length, the prefix and suffix are the same. We will break the outer for loop and store the result in a variable.
  7. Now, simply print the length.

Java Program to find the length of the longest prefix in a string which is also a suffix

import java.util.Scanner;
public class LongestSuffixPrefix 
{
    public static void main(String[] args) 
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a string:");
        String s=sc.next();
        int n=s.length();
        int res=0;
        for(int i=n/2;i>=0;i--)
        {
            boolean flag=true;
            int j,k;
            for(j=0,k=i+1;j<i && k<n;j++,k++)
            {
                if(s.charAt(j)!=s.charAt(k))
                {
                    flag=false;
                    break;
                }
            }
            if(flag)
            {
                res=i;
                break;
            }
        }
        System.out.println("The length of the longest suffix and prefix is: "+res);
    }
}

Output of program to find the length of the longest prefix in a string which is also a suffix