Leetcode 500. Keyboard Row

用到一个Python知识点:

两个set可以比大小来表示是不是子集.

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

写的更Pythonic一点:

class Solution(object):
    def findWords(self, words):
        return list(filter(lambda w: any([set(w.lower()) <= set('qwertyuiop'), set(w.lower()) <= set('asdfghjkl'),set(w.lower()) <= set('zxcvbnm')]), words))
        

 

posted @ 2019-03-21 02:44  周洋  阅读(229)  评论(0编辑  收藏  举报