Find the length longest common prefix.

How to find the length longest common prefix?

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : “gee”

1 Like

No. output : 3 (length of gee).

Here’s a java code for your question, please let me know if this helps you

public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0){
    return "";
}

if(strs.length==1) 
    return strs[0];

int minLen = strs.length+1;

for(String str: strs){
    if(minLen > str.length()){
        minLen = str.length();
    }
}

for(int i=0; i<minLen; i++){
    for(int j=0; j<strs.length-1; j++){
        String s1 = strs[j];
        String s2 = strs[j+1];
        if(s1.charAt(i)!=s2.charAt(i)){
            return s1.substring(0, i);
        }
    }
}

return strs[0].substring(0, minLen);

}

PLEASE FOLLOW THE LINK FOR DETAILED EXPLAINATION

 #include<bits/stdc++.h>
 using namespace std;

string commonPrefixUtil(string str1, string str2)
{
    string result;
   int n1 = str1.length(), n2 = str2.length();
   for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
   {
       if (str1[i] != str2[j])
           break;
       result.push_back(str1[i]);
   }
   return (result);

}

 string commonPrefix (string arr[], int n)
{
  string prefix =  arr[0];
  for (int i=1; i<=n-1; i++)
    prefix = commonPrefixUtil(prefix, arr[i]);

return (prefix);

}

int main()
{
  string arr[] = {"geeksforgeeks", "geeks",
                "geek", "geezer"};
  int n = sizeof(arr) / sizeof(arr[0]);

  string ans = commonPrefix(arr, n);

  if (ans.length())
      printf ("The longest common prefix is - %s",
              ans.c_str());
  else
     printf("There is no common prefix");

 return (0);

}

1 Like

main function???