LeetCode500. Keyboard Row

来源:互联网 发布:上帝在掷骰子吗 知乎 编辑:程序博客网 时间:2024/06/01 07:42
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

【题目】
对于输入的单词list,如果单词的每个字母都是在键盘上的一行内,则返回这种单词的list。
【解法1】
对每个单词拆解成元素集,分别与每行字母组成的元素集,进行取交集,如果返回的结果为原单词的元素(也就是单词是键盘行的子集),则认为这个单词满足条件。
  • python的set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交、差、对称差等
  • 对list取交集为‘&’, 并集为'|'
class Solution(object):    def findWords(self, words):        """        :type words: List[str]        :rtype: List[str]        """        row_1=set('qwertyuiop')        row_2=set('asdfghjkl')        row_3=set('zxcvbnm')                ans=[]                for i in words:            word=set(i.lower())            if word&row_1 == word :                ans.append(i)            elif word&row_2 == word:                ans.append(i)            elif word&row_3==word:                ans.append(i)                        return ans
【解法2】
正则匹配
re.compile:编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
filter()函数:用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
class Solution(object):    def findWords(self, words):        """        :type words: List[str]        :rtype: List[str]        """    return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)