Answers for "how to implement lcm in c#"

C#
1

c# LCP

public static string LCP(string[] words)
        {
            string result = "";

            if (words.Length == 0 || words == null) return "None in common";
            // shortest to longest by word count ... optional
            var orderedWords = words.OrderBy(x => x.Length)
            				  .ToArray();

            for (int i = 0; i < words.Length - 1; i++)
            {
                //hold each word to compare against 1st word
                string fixedWord = words[0].Substring(0, i + 1);

                for (int j = 1; j < words.Length; j++)
                {
                    //compare 1st word by letter against each other word
                    string currentWord = words[j].Substring(0, i + 1);

                    if (fixedWord == currentWord)
                    {
                        // just the char's that match
                        result = currentWord;
                    }
                    else if (fixedWord != currentWord)
                    {
                        return result.Substring(0, currentWord.Length - 1);
                    }
                }
            }
            return result;

        }
Posted by: Guest on June-26-2020

C# Answers by Framework

Browse Popular Code Answers by Language