1. 程式人生 > >leetcode python 500.鍵盤行(簡單、字串)

leetcode python 500.鍵盤行(簡單、字串)

給定一個單詞列表,只返回可以使用在鍵盤同一行的字母打印出來的單詞。

輸入: [“Hello”, “Alaska”, “Dad”, “Peace”]
輸出: [“Alaska”, “Dad”]

def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        s1=list('qwertyuiopQWERTYUIOP')
        s2=list('ASDFGHJKLasdfghjkl')
        s3=list('ZXCVBNMzxcvbnm')
        s=[]
        for i in words:
            a=b=c=0
            for j in set(i):
                a+=int(j in s1)
                b+=int(j in s2)
                c+=int(j in s3)
            if a==len(set(i)) or b==len(set(i)) or c==len(set(i)):
                s.append(i)
        return s

執行用時: 28 ms, 在Keyboard Row的Python提交中擊敗了43.84% 的使用者

def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        line1="qwertyuiop"
        line2="asdfghjkl"
        line3="zxcvbnm"
        ans=[]
        for word in words:
            temp = word.lower()
            if (self.findWord(temp, line1)):
                ans.append(word)
            elif(self.findWord(temp,line2)):
                ans.append(word)
            elif(self.findWord( temp, line3)):
                ans.append(word)
        return ans  
    def findWord(self, word,base):
        for char in word:
            if char not in base:
                return False
        return True   

執行時用了20ms
兩個其實差別不大,都用了兩次迴圈