LeetCode 500. Keyboard Row

    xiaoxiao2021-03-25  75

    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.

    HashTable,把字符存储到哈希表中。

    解法一:

    class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ dict1 = {'q':1,'w':1,'e':1,'r':1,'t':1,'y':1,'u':1,'i':1,'o':1,'p':1} dict2 = {'a':1,'s':1,'d':1,'f':1,'g':1,'h':1,'j':1,'k':1,'l':1} dict3 = {'z':1,'x':1,'c':1,'v':1,'b':1,'n':1,'m':1} list1 = [] for word in words: inalpha = -1 succ = True if word[0].lower() in dict1: inalpha = 1 elif word[0].lower() in dict2: inalpha = 2 elif word[0].lower() in dict3: inalpha = 3 if inalpha == -1: continue for a in word: if inalpha == 1: if a.lower() not in dict1: succ = False break elif inalpha == 2: if a.lower() not in dict2: succ = False break elif inalpha == 3: if a.lower() not in dict3: succ = False break if succ == True: list1.append(word) return list1 当我知道了解法二,崩溃。。。

    class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ set1 = set('qwertyuiop') set2 = set('asdfghjkl') set3 = set('zxcvbnm') list1 = [] for word in words: w = set(word.lower()) if w.issubset(set1) or w.issubset(set2) or w.issubset(set3): list1.append(word) return list1

    转载请注明原文地址: https://ju.6miu.com/read-35902.html

    最新回复(0)