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)
  • 相关阅读:
    福大软工 · 第十次作业
    Summary #ToBeContinue......
    福大软工 · 第十二次作业
    Beta 冲刺(7/7)
    Beta 冲刺(6/7)
    Beta 冲刺(5/7)
    Beta 冲刺(4/7)
    Beta 冲刺(3/7)
    Beta 冲刺(2/7)
    福大软工 · 第十次作业
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501774.html
Copyright © 2011-2022 走看看