w3resource

Java: Find the longest substring appears at both ends of a given string


93. Longest Prefix and Suffix Substring

Write a Java program to find the longest substring that appears at both ends of a given string.

Visual Presentation:

Java String Exercises: Find the longest substring appears at both ends of a given string


Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {

  // Method to find the longest substring that appears at both ends of the given string
  public String appearInBothEnds(String stng) {
    int l = stng.length(); // Get the length of the given string
    String f_str = ""; // Initialize a string to store the found substring
    String tmp = ""; // Initialize a temporary string

    // Loop through the characters of the given string
    for (int i = 0; i < l; i++) {
      tmp += stng.charAt(i); // Add the current character to the temporary string
      int t_len = tmp.length(); // Get the length of the temporary string

      // Check if the temporary string is present both at the beginning and end of the main string
      if (i < l / 2 && tmp.equals(stng.substring(l - t_len, l))) {
        f_str = tmp; // Update the found substring if a match is found
      }
    }
    return f_str; // Return the longest substring appearing at both ends of the string
  }

  // Main method to execute the program
  public static void main(String[] args) {
    Main m = new Main(); // Create an instance of the Main class

    String str1 = "playersplay"; // Given string
    // Display the given string and the longest substring appearing at both ends
    System.out.println("The given string is: " + str1);
    System.out.println("The longest substring in the string is: " + m.appearInBothEnds(str1));
  }
}

Sample Output:

The given string is: playersplay
The longest substring in the string is: play

Flowchart:

Flowchart: Java String Exercises - Find the longest substring appears at both ends of a given string



For more Practice: Solve these Related Problems:

  • Write a Java program to identify the longest substring that is both a prefix and a suffix of a given string.
  • Write a Java program to find and return the maximum length border substring in a string.
  • Write a Java program to compute the longest common prefix and suffix of a string.
  • Write a Java program to determine the longest substring that occurs at both the beginning and the end of the input.

Go to:


PREV : Remove All Instances of Substring.
NEXT : Longest Mirror Image Substring.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.