Find Longest Common Prefix (LCP) of string

By   Tewodros   Date Posted: Mar. 2, 2022  Hits: 1,044   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of strings that may or many not have a common prefix, we wan to find the longest common prefix.

Example:

Input = { “Hospital”, “Host”, “Hostage”}

Ans: Hos

Solution:

We can use the “StartsWith” string function to make our lives easier.

Basically we will make initial assumption and make the first string as a common prefix.

We then iterate through each string (1,2…) starting from index 1 and check if it starts with our string at 0 index (common prefix)

If it doesn't start with it, then we will remove one char from the end of the common prefix and keep checking until it does.

 

 public string LongestCommonPrefix(string[] strs) {

       string common = strs[0];

       for(int i=1; i < strs.Length; i++)   {

           while(!strs[i].StartsWith(common))     {

               common = common.Substring(0, common.Length-1);

           }

       }       

       return common;

   } 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* zpaxhu

Back to Top