python--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.


American keyboard


Example 1:

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

Note:

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

这题的意思就是输入一个list,list的元素为字符串,判断每一个字符串能否用键盘上的一行打出来,返回每一个可以的字符串。

我按照题意随便写了一个,感觉比较蠢:

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        list1=['q','w','e','r','t','y','u','i','o','p']
        list2=['a','s','d','f','g','h','j','k','l']
        list3=['z','x','c','v','b','n','m']
        res=[]
        a=[1 for n in range(len(words))]
        b = [0 for n in range(len(words))]
        for i in range(len(words)):
            for j in range(len(words[i])):
                if words[i][j] in list1:
                    if b[i]==0 or b[i]==1 :b[i]=1
                    else: a[i]=0
                if words[i][j] in list2:
                    if b[i]==0 or b[i]==2:b[i]=2
                    else: a[i]=0
                if words[i][j] in list3:
                    if b[i]==0 or b[i]==3:b[i]=3
                    else: a[i]=0
        for i in range(len(a)):
            if a[i]==1:
                 res.append(words[i])
        return res

s=Solution()
s.findWords(['hello','sf','aaaa','qwcd'])
思路就是暴力去求是否能用一行打出,用b数组来记录用哪一行键盘打,如果不止用一行键盘则置a数组对应的元素为0。

当然还有更屌的解法:

def findWords(self, words):
    return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)

re.compile:编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
filter()函数:用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值