top of page
Writer's pictureBhimubgm

Find longest common prefix between two strings.

Understanding the problem:

We are going to find the longest prefix between any two strings given. If no common prefix is found then output should be NULL. Check out following examples for better understanding.

Ex1: Input: "findLongestCommonPrefix" and "findLongestCommonSuffix"

Output: findLongestCommon

Ex2: Input: "tyhtgaerge" and "gfhjwertw"

Output: NULL

Approach:

Our program takes two input strings and computes the longest common suffix between these two. As we have to find prefix, we start from the beginning of the strings. Keep comparing the characters from the start of the both strings moving towards the end by one index each time. Every time we have match, increment the suffix length by one. Once we find non matching characters, we have found the longest common suffix, exit the loop. Lets make sure suffix length is greater than zero. If zero, no common suffix, output - NULL. Else, compute suffix using sub-string. At the end you have the desired output. Lets ave a look at flowchart below. Feel free to post your comments or opinions in the comment section below.


Flowchart:

Flowchart for finding longest common prefix between two strings
Flowchart for finding longest common prefix between two strings

Java Code:

package com.bhimubgm.example;


public class LongestCommonPrefix {

public static void main(String[] args) {

System.out.println(findLongestCommonPrefix("findLongestCommonPrefix", "findLongestCommonSuffix"));

}

public static String findLongestCommonPrefix(String s1, String s2) {

int m = 0, n = 0;

// Store length of longest prefix

int l = 0;

while(m < s1.length() && n < s2.length()){

if(s1.charAt(m++) == s2.charAt(n++)){

l++;

} else {

break;

}

}

// There is no common prefix

if(l == 0){

return "NULL";

}

// Stores longest prefix

return s1.substring(0, l);

}

}



85 views0 comments

Comments


bottom of page