How to Find the Longest Common Prefix of Two Strings in Java?
Last Updated :
25 Apr, 2024
In this article, we will find the longest common prefix of two Strings in Java.
Examples:
Input: String 1= geeksforgeeks, String 2 = geezer
Output: “gee”
Input: String 1= flower, String 2 = flight
Output: “fl”
Methods to Find the Longest common Prefix of two Strings in Java
Below are the methods by which we can find the longest common prefix of two Strings.
- Using a loop to compare characters
- Using the
startsWith
method - Using a recursive approach
1. Loop to Compare Characters
Here we use a loop to perform this comparison and construct the longest common prefix by appending matching characters to a StringBuilder. Once a mismatch is encountered, the loop breaks and the method returns the constructed prefix.
Below is the program to Find the Longest common Prefix of two Strings:
Java
public class LongestCommonPrefix {
public static String longestCommonPrefix(String str1, String str2) {
// Find the smaller length between the
// two strings to ensure comparison within bounds
int minLength = Math.min(str1.length(), str2.length());
// Use StringBuilder for efficient string manipulation
StringBuilder prefix = new StringBuilder();
// Loop through both strings until the minimum length
for (int i = 0; i < minLength; i++) {
// Break the loop if characters do not match
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
// Append the matching character to the prefix
prefix.append(str1.charAt(i));
}
// Convert StringBuilder to String and return
return prefix.toString();
}
public static void main(String[] args) {
// Prepare two strings to find their
// longest common prefix
String str1 = "flower";
String str2 = "flight";
// Determine the longest common
// prefix and display it
String longestPrefix = longestCommonPrefix(str1, str2);
System.out.println("Longest Common Prefix: " + longestPrefix);
}
}
OutputLongest Common Prefix: fl
2. startsWith Method
This method checks if one string starts with another string. It iterates through the characters until a mismatch is found, and then returns the prefix formed by the characters that matched until that index.
Below is the program to Find the Longest common Prefix of two Strings:
Java
public class LongestCommonPrefix {
public static String longestCommonPrefix(String str1, String str2) {
// Determine the minimum length
// between the two strings to limit the comparison
int minLength = Math.min(str1.length(), str2.length());
// Iterate through the strings up to the minimum length
for (int i = 0; i < minLength; i++) {
// If characters at the current index are not
// the same, return the substring up to that point
if (str1.charAt(i) != str2.charAt(i)) {
// Return prefix until mismatch
return str1.substring(0, i);
}
}
// If all characters match up to the
// minimum length, return the entire substring
return str1.substring(0, minLength);
// Return prefix if no mismatch
}
public static void main(String[] args) {
// Initialize two strings for comparison
String str1 = "flower";
String str2 = "flight";
// Call the method to find and
// print the longest common prefix
String longestPrefix = longestCommonPrefix(str1, str2);
System.out.println("Longest Common Prefix: " + longestPrefix);
}
}
OutputLongest Common Prefix: fl
3. Recursive approach
If the substrings at a certain length are equal, it returns that substring as the common prefix. Otherwise, it recursively calls itself with a smaller length until it finds the longest common prefix.
Below is the program to Find the Longest common Prefix of two Strings:
Java
public class LongestCommonPrefix {
public static String longestCommonPrefix(String str1, String str2) {
// Initialize the minimum length variable
// with the minimum of the two string lengths
int minLength = Math.min(str1.length(), str2.length());
// Call the recursive method to find the longest common prefix
return longestCommonPrefixRecursive(str1, str2, minLength);
}
private static String longestCommonPrefixRecursive(String str1, String str2, int length) {
// if length is 0
// return an empty string
if (length == 0) {
return "";
}
// If the substrings of the current
// length are equal, return the substring
else if (str1.substring(0, length).equals(str2.substring(0, length))) {
return str1.substring(0, length);
} else {
// Otherwise, decrease the length
// by 1 and call the method recursively
return longestCommonPrefixRecursive(str1, str2, length - 1);
}
}
public static void main(String[] args) {
// Define two strings to find their longest common prefix
String str1 = "flower";
String str2 = "flight";
// Call the method to find the longest common prefix and print it
String longestPrefix = longestCommonPrefix(str1, str2);
System.out.println("Longest Common Prefix: " + longestPrefix);
}
}
OutputLongest Common Prefix: fl
Similar Reads
Java Program To Find Longest Common Prefix Using Sorting Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read
How to Find the Intersection of Two Strings in Java? We know that the Strings are a collection of characters so if we want to find the intersection of two Strings the simple way is we can compare each character of the first String with the characters of the Second String. Example to Find the Intersection of Two Strings in JavaThere are two strings ava
2 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching Given a set of strings, find the longest common prefix. Examples: Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on âPRACTICE â first, before moving on to the solution. We start with an example. Suppose
5 min read
Java Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
8 min read
How to Calculate the Levenshtein Distance Between Two Strings in Java Using Recursion? In Java, the Levenshtein Distance Algorithm is a pre-defined method used to measure the similarity between two strings and it can be used to calculate the minimum number of single-character edits (inserts, deletions, or substitutions) required to change one string into another. Prerequisites: Recurs
4 min read