首页 > 学院 > 开发设计 > 正文

Leetcode-Algorithms Keyboard Row

2019-11-08 02:08:06
字体:
来源:转载
供稿:网友

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)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表