leetcode 500. Keyboard Row(python)

198 阅读1分钟

描述

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.

解析

根据题意,要从列表 words 中找出能由同一行字母形成的单词,只需要事先定义好三种不同的字符集字符串,然后逐个遍历 words ,判断单词中出现的字符,是不是这三种不同字符集字符串的任意一个的子集,如果是则将结果追加到 result 中,遍历结束即可得到答案。

解答

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        row1 = 'qwertyuiopQWERTYUIOP'
        row2 = 'asdfghjklASDFGHJKL'
        row3 = 'zxcvbnmZXCVBNM'
        result = []
        for word in words:
            if set(word).issubset(row1):
                result.append(word)
            elif set(word).issubset(row2):
                result.append(word)
            elif set(word).issubset(row3):
                result.append(word)
        return result
        	      
		

运行结果

Runtime: 8 ms, faster than 100.00% of Python online submissions for Keyboard Row.
Memory Usage: 13.4 MB, less than 73.37% of Python online submissions for Keyboard Row.

原题链接:leetcode.com/problems/ke…

您的支持是我最大的动力