C#: How can this possibly be made faster?


  • 0
    M

    Somehow, this solution only beats 3% of the previous submissions, but I can't think of a way to make it faster. Any suggestions?

    (I think (read: I hope) they added new use-cases which make newer submissions seem slower than older submissions.)

    public class Solution {
        
        public static int[] keyboardRow = new int[26] { 3, 4, 4, 3, 2, 3, 3, 3, 2, 3, 3, 3, 4, 4, 2, 2, 2, 2, 3, 2, 2, 4, 2, 4, 2, 4 };
        
        public static char ToLower(char c)
        {
            int diff = c - 'A';
            // This condition checks whether the input character was an capital letter character or not.
            if (diff >= 26 || diff < 0)
            {
                // If the input was not a capital letter, the original character is returned.
                return c;
            }
            // If the letter was a capital letter, the lowercase equivalent is returned.
            return (char)('a' + diff);
        }
            
        public string[] FindWords(string[] words) {
            var list = new List<string>(words.Length);
            
            foreach (var word in words)
            {
                //if (String.IsNullOrEmpty(word))
                //    continue;
                
                int nominatedRow = keyboardRow[ToLower(word[0]) - 'a'];
                int i;
                for (i = 1; i < word.Length && keyboardRow[ToLower(word[i]) - 'a'] == nominatedRow; i++)
                {
                    // Continue checking the letters.
                    // Later, the index of this loop will be used to test whether the whole word is from the nominatedRow.
                }
                // If we reached the end of the word, then the word was typed using only the letters from a single row.
                if (i == word.Length)
                {
                    list.Add(word);
                }
            }
            return list.ToArray();
        }
    }
    

Log in to reply
 

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