C# - sort and find - brute force - simple


  • 1

    This is basically a brute force method. The only optimization is to sort the dictionary by word length then by alphabetical. Once sorted just got through from longest and check for matching using 2 pointers. There is nothing fancy about this solution.

        public string FindLongestWord(string s, IList<string> d) 
        {
            foreach (string x in d.OrderByDescending(x => x.Length).ThenBy(x => x))
            {
                int i1 = 0;
                int i2 = 0;
                while (i1 < x.Length && i2 < s.Length)
                {
                    if (x[i1] == s[i2])
                    {
                        i1++;
                        i2++;
                    }
                    else
                    {
                        i2++;
                    }
                }
                
                if (i1 == x.Length) return x;
            }
            
            return "";
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.