Friday, September 11, 2020

Write a function to find the longest common prefix string amongst an array of strings.

public string LongestCommonPrefix(string[] strs) 

{

        if (strs == null || strs.Length <= 0)

            {

                return string.Empty;

            }

            string result = string.Empty;

            int i = 0;

            while (i < strs[0].Length)

            {

                char currChar = strs[0][i];

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

                {

                    if (i == strs[j].Length || currChar != strs[j][i])

                    {

                        return result;

                    }

                }

                result += currChar;

                ++i;

            }

            return result;

}

No comments:

Post a Comment