Leetcode-Algorithms 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”]

给一个有一些单词的list,返回一个包含可以在美式键盘上只用其中一行字母就可以打出来的单词的list。(q-p,a-l,z-m)
一开始想到的最蠢的办法是给三行字母创建三个list用loop一个字母一个字母的检测是不是在这个list里面。后来看到了用正则表达式(regex)来判断的简便方法。

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        result=[]
        for w in words:
            new_word = w.lower()
            rst1 = re.match('[qwertyuiop]*',new_word).group(0)
            rst2 = re.match('[asdfghjkl]*',new_word).group(0)
            rst3 = re.match('[zxcvbnm]*',new_word).group(0)
            if rst1 != None:
                if rst1 == new_word:
                    result.append(w)
                elif rst2 == new_word:
                    result.append(w)
                elif rst3 == new_word:
                    result.append(w)
        return result

附上leetcode上的答案:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值