[leetcode: Python]500.Keyboard Row

来源:互联网 发布:怎么写好网络小说知乎 编辑:程序博客网 时间:2024/06/05 15:36

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.

American keyboard
这里写图片描述

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]Output: ["Alaska", "Dad"]

Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.

方法一:55ms

class Solution(object):    def findWords(self, words):        """        :type words: List[str]        :rtype: List[str]        """        wset = map(set,['qwertyuiop','asdfghjkl','zxcvbnm'])        ans = []        for word in words:            wordi = set(word.lower())            if any(wordi <= rset for rset in wset):                ans.append(word)        return ans

方法二:42ms

class Solution(object):    def findWords(self, words):        """        :type words: List[str]        :rtype: List[str]        """        keyboard = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]        out = []        for i in words:            for line in keyboard:                lword = i.lower()                if set(lword).issubset(set(line)):                    out.append(i)        return out
原创粉丝点击