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)
  • 相关阅读:
    lombok 下的@Builder注解用法
    (springboot)自定义Starter
    各种 Spring-Boot-Starters系列 介绍
    MQ的使用场景
    SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用
    RPC原理详解
    Java性能优化的50个细节
    thinkphp3.2.2有预览的多图上传
    关于php中的exec命令
    关于thinkphp3.1无法加载模块解决办法
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501774.html
Copyright © 2011-2022 走看看