C#, longer solution compared to others, but may be easy to understand


  • 0
    B
    public class Solution {
        public string[] FindWords(string[] words) {
            HashSet<char> topRow = new HashSet<char>() {
                'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
            };
            
            HashSet<char> middleRow = new HashSet<char>() {
                'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
            };
            
            HashSet<char> bottomRow = new HashSet<char>() {
                'z', 'x', 'c', 'v', 'b', 'n', 'n', 'm',
            };
            
            List<string> resultList = new List<string>();
            
            for(int i = 0; i < words.Length; i++) {
                string word = words[i];
                int previousRow = -1;
                bool isValid = true;
                
                for(int j = 0; j < word.Length; j++) {
                    int currentRow = -1;
                    char letter = Char.ToLower(word[j]);
                    
                    if(topRow.Contains(letter)) {
                        currentRow = 0;
                    }
                    else if(middleRow.Contains(letter)) {
                        currentRow = 1;
                    }
                    else if(bottomRow.Contains(letter)) {
                        currentRow = 2;
                    }
                    
                    if(previousRow != -1 && currentRow != previousRow) {
                        isValid = false;
                        break;
                    }
                    else {
                        previousRow = currentRow;
                    }
                }
                
                if(isValid) {
                    resultList.Add(word);
                }
            }
            
            return resultList.ToArray();
        }
    }
    

    This works by iterating through each character of each word. I use three different hash sets to look up the row of the character. I keep track of the row that each character is on and compare them to each other as I iterate through the characters. If at any pointer the row doesn't match the previous character's row, we know that it's not a valid word so we can break out and move to the next word.


Log in to reply
 

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