Two Clear Pythonic Solutions using Sets and Dicts


  • 0
    M

    Dict and Set:

    class Solution(object):
        def findWords(self, words):
            """
            :type words: List[str]
            :rtype: List[str]
            """
            
            keyboard = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]
            d = dict()
            
            for line in keyboard:
                for letter in line:
                    d[letter] = line
            
            ret = []
            for word in words:
                w = word.lower()
                line = d[w[0]]
                if all(map(lambda letter: letter in line, w)):
                    ret.append(word)
            
            return ret
    

    Just sets

    class Solution(object):
        def findWords(self, words):
            """
            :type words: List[str]
            :rtype: List[str]
            """
            
            keyboard = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]
            
            ret = []
            for word in words:
                letters = set(word.lower())
                for line in keyboard:
                    if letters & line == letters:
                        ret.append(word)
            return ret
    

Log in to reply
 

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