【Leetcode】500. Keyboard Row

【Leetcode】500. Keyboard Row_第1张图片

class Solution1(object):
    def findWords(self, words):
        """
        use set
        """
        set1 = set('qwertyuiop')
        set2 = set('asdfghjkl')
        set3 = set('zxcvbnm')
        result = []
        for word in words:
            word_set = set(word.lower())
            if word_set.issubset(set1) or word_set.issubset(set2) or word_set.issubset(set3):
                result.append(word)
        return result

class Solution2(object):
    """
    use all any lambda and filter function
    """
    def findWords(self, words):
        r1 = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
        r2 = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
        r3 = ['z', 'x', 'c', 'v', 'b', 'n', 'm']
        is_true = lambda  word: any([all(i in r1 for i in word.lower()), all(i in r2 for i in word.lower()), all(i in r3 for i in word.lower())])
        return list(filter(is_true, words))

class Solution3(object):
    """
    use regular expression (regex)
    (?i):  case-insensitive  (不区分大小写)
    $: match all, not part macth
    """
    def findWords(self, words):
        import re
        def match(word):
            return re.compile("(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$").match(word)
        return list(filter(match, words))

你可能感兴趣的:(LeetCode)