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
两个其实差别不大,都用了两次循环

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84786843