zoukankan      html  css  js  c++  java
  • leetcode算法: Keyboard Row

    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.


    American keyboard


    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.


    这道题描述的是:
    给定一些单词,让我们找出这些单词中哪些单词是 所有字母都在键盘同一行上


    qwertyuiop是键盘的第一行
    asdfghjkl是键盘的第二行
    zxcvbnm是键盘第三行


    刚拿到这道题还真的很头疼- -难道要对单词每个字母进行遍历吗??

    后来参考了其他大神的思想,大致是两种思路,一种是正则表达式匹配,另一种是集合思想。
    我用了集合的思想。用三个集合分别存下键盘个行的所有字母。
    当给定一个单词 我们看看这个单词是不是这三个集合某一个的子集,如果是,那这个单词就满足字母都在一行

    我的代码:
     1 class Solution(object):
     2     def findWords(self, words):
     3         """
     4         :type words: List[str]
     5         :rtype: List[str]
     6         """
     7         q,a,z = set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")
     8         res = []
     9         for str in words:
    10             lset = set(str.lower() )
    11             if lset.issubset(q) or lset.issubset(a) or lset.issubset(z):
    12                 res.append(str)
    13         return res
    14 
    15 
    16 
    17 if __name__ == '__main__':
    18     s = Solution()
    19     res = s.findWords(["Hello", "Alaska", "Dad", "Peace"])
    20     print(res)
  • 相关阅读:
    C# Linq 类似Scala中的map的函数
    Spark DataFrame NOT IN实现方法
    Scala scopt 命令行解析
    WPF 绑定到静态属性,可通知
    WPF GroupBox Header居中
    WPF开源项目整理(排名不分先后)
    Windows 上配置 Go 的 gRPC 编译环境
    C++20新线程 jthread 体验代码
    查找被删除但仍然占据磁盘的文件
    以Docker方式安装Redis集群
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501774.html
Copyright © 2011-2022 走看看