leetcode500. Keyboard Row

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.

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.

1、简短的答案 any 和 all

主要用到了python中的all和any函数,所以整个过程非常简单

class Solution(object):
    def findWords(self, words):
        l=['qwertyuiop','asdfghjkl','zxcvbnm']
        res=[]
        for w in words:
            if any(all(c in ll for c in w.lower()) for ll in l): # Exists(ll in l) ForAny(c in w) SuchThat(c in ll)
                res.append(w)
        return res

2、集合解法1 issubset()

class Solution:
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        row1 = set('qwertyuiop')
        row2 = set('asdfghjkl')
        row3 = set('zxcvbnm')
        res = []
        for each in words:
            target = set(each.lower())
            if target.issubset(row1) or target.issubset(row2) or target.issubset(row3):
                res.append(each)
        return res

3、集合解法2

    myList = list()
    for word in words:
        a = {'q','w','e','r','t','y','u','i','o','p'}
        b = {'a','s','d','f','g','h','j','k','l'}
        c = {'z','x','c','v','b','n','m'}
        myBool = True
        for letter in word:
            if letter.lower() in a:
                b = a
                c = a
            elif letter.lower() in b:
                a = b
                c = b
            elif letter.lower() in c:
                a = c
                b = c
            else:
                myBool = False
        if myBool == True:
            myList.append(word)
    return myList

4、我的答案

class Solution:
    def findWords(self, words):
        result=[]
        
        def isinstr(keys,word1):
            flag=True
            for alpha in word1:
                    if alpha not in keys:
                        flag=False
                        break
            return flag
        keylist=['asdfghjkl','qwertyuiop','zxcvbnm']
        for word in words:
            word1=word.lower()
            for keys in keylist:
                if word1[0] in keys:
                    if isinstr(keys,word1):
                        result.append(word)
                        break             
        return result
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值