leetcode500鍵盤行python實現

1.問題描述


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

American keyboard

示例:

輸入: ["Hello", "Alaska", "Dad", "Peace"]
輸出: ["Alaska", "Dad"]
 

注意:

你可以重複使用鍵盤上同一字符。
你可以假設輸入的字符串將只包含字母。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/keyboard-row
 

2.python實現

第一遍錯誤實現

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        one = ['q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P']
        two = ['a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L']
        three = ['z','x','c','v','b','n','m','Z','X','C','V','B','N','M']
        for word in words:
            flag = list()
            index = 0
            for c,i in zip(word,range(len(word))):
                if c in one:
                    flag.append(1)
                elif c in two:
                    flag.append(2)
                else:
                    flag.append(3)
                if i!=0 and flag[i-1]!=flag[-1]:
                    index = -1
                    break
            if index==-1:
                words.remove(word)
        return words
                
                    

第二遍正確的

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        one = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P']
        two = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L']
        three = ['z', 'x', 'c', 'v', 'b', 'n', 'm', 'Z', 'X', 'C', 'V', 'B', 'N', 'M']
        re_list = list()
        for word in words:
            flag = list()
            index = 0
            for c, i in zip(word, range(len(word))):
                if c in one:
                    flag.append(1)
                elif c in two:
                    flag.append(2)
                else:
                    flag.append(3)
                if i != 0 and flag[i - 1] != flag[-1]:
                    index = -1
                    break
            if index == 0:
                re_list.append(word)
        return re_list

3.遇到的問題

for循環中關於列表list中remove的坑(特別注意見鏈接 https://blog.csdn.net/qq_36387683/article/details/86659222

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章