500. Keyboard Row
来源:互联网 发布:mac os x10.10.5迅雷 编辑:程序博客网 时间:2024/06/07 13:29
500. 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.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.
解1:
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ rows = ["qwertyuiop", "asdfghjkl","zxcvbnm"] output = [] for word in words: #word = word.lower() for row in rows: #row = row.lower() num = 0 for char in word.lower(): for row_char in row.lower(): if char == row_char: num += 1 break #这里加个这个,匹配到一个以后推出本次循环 if num == len(word): output.append(word) break return output
这种应该是最笨的方法了,其中需要把判断的字符都转换为小写(string.lower() ),排名在34%。
解2:
还可以用set()来解,因为set()是所有出现过的字符,如果两个集合的交集等于单词的集合,那么这两个字符就匹配。
def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ a=set('qwertyuiop') b=set('asdfghjkl') c=set('zxcvbnm') ans=[] for word in words: t=set(word.lower()) if a&t==t: ans.append(word) if b&t==t: ans.append(word) if c&t==t: ans.append(word) return ans
0 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row (E)
- 500. Keyboard Row
- 500. Keyboard Row
- leetcode 500. Keyboard Row
- 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- 500. Keyboard Row
- 【浅谈轮廓线DP】BZOJ1087(SCOI2005)[互不侵犯King]题解
- Android Canvas绘图详解
- 228. Summary Ranges 题解
- 继续聊WPF——进度条
- Problem C: 合唱比赛开始了!
- 500. Keyboard Row
- OpenCV中对矩阵的行列操作的解决方法
- 继续聊WPF——Thumb控件
- 开发nginx模块时对普通文件的操作
- owncloud 私有云搭建
- CentOS7 安装Python3
- 蓝桥杯 Log大侠 题解
- 计算几何基础NYOJ——67三角形面积
- jsp本地打开