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)新聞熱點
疑難解答