LeetCode500. Keyboard Row
来源:互联网 发布:上帝在掷骰子吗 知乎 编辑:程序博客网 时间:2024/06/01 07:42
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.
【题目】
对于输入的单词list,如果单词的每个字母都是在键盘上的一行内,则返回这种单词的list。
【解法1】
对每个单词拆解成元素集,分别与每行字母组成的元素集,进行取交集,如果返回的结果为原单词的元素(也就是单词是键盘行的子集),则认为这个单词满足条件。
- python的set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交、差、对称差等
- 对list取交集为‘&’, 并集为'|'
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ row_1=set('qwertyuiop') row_2=set('asdfghjkl') row_3=set('zxcvbnm') ans=[] for i in words: word=set(i.lower()) if word&row_1 == word : ans.append(i) elif word&row_2 == word: ans.append(i) elif word&row_3==word: ans.append(i) return ans
【解法2】
正则匹配
re.compile:编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
filter()函数:用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)
阅读全文
0 0
- leetcode500: Keyboard Row
- leetcode500 Keyboard Row Java
- Leetcode500. Keyboard Row
- leetcode500. Keyboard Row
- LeetCode500. Keyboard Row
- Leetcode500. Keyboard Row
- python--leetcode500. Keyboard Row
- 14.leetCode500:keyboard row
- LeetCode500. Keyboard Row我的C++解法
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- 数据结构8:希尔排序专题
- Java 生成随机日期,时间
- Codeforces-417D总结&题解
- servletServletConfigAndServletContext
- CF734E:Anton and Tree(缩点 & 直径)
- LeetCode500. Keyboard Row
- 轻松将电气数据集成到您的机械设计
- CodeForces
- a.length==0、a==null、a == ""、a.equals("") 的区别
- vue中的video
- 【引用】web性能测试基本知识
- leetcode-26&80 Remove Duplicates from Sorted Array I & II
- hdu 6058 链表 枚举
- 我们是如何在一个月内干掉腾讯阅读的