[leetcode]: 500. Keyboard Row
来源:互联网 发布:华为mate10抢购软件 编辑:程序博客网 时间:2024/06/07 01:09
1.题目描述
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard
Example 1:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
翻译:给一个单词列表,输出所有字母均在同一行的单词。
2.分析
输入只有字母,所以将键盘分为三行。
第一行:【’Q’,’W’,’E’,’R’,’T’,’Y’,’U’,’I’,’O’,’P’】
第二行:【’A’,’S’,’D’,’F’,’G’,’H’,’J’,’K’,’L’】
第三行:【’Z’,’X’,’C’,’V’,’B’,’N’,’M’】
要查找一个单词中所有字母是否在同一行,有两种方式:
1.为每一行字符建立一个哈希表,通过哈希表查找
2.使用STL的set容器,可以查找一个元素是否在set中。
3.代码
C++
这里实现的是为每一行字符建立哈希表。因为有区分大小写,所以把大小写字母都加进了哈希表。代码有点长。
vector<string> findWords(vector<string>& words) { bool** hashTable = new bool*[3]; for (int i = 0; i < 3; i++) hashTable[i] = new bool[256](); char one[20] = { 'Q','W','E','R','T','Y','U','I','O','P','q','w','e','r','t','y','u','i','o','p' }; char two[18] = { 'A','S','D','F','G','H','J','K','L','a','s','d','f','g','h','j','k','l' }; char three[14] = { 'Z','X','C','V','B','N','M','z','x','c','v','b','n','m' }; for (int i = 0; i < 20; i++) hashTable[0][one[i]] = 1; for (int i = 0; i < 18; i++) hashTable[1][two[i]] = 1; for (int i = 0; i < 14; i++) hashTable[2][three[i]] = 1; vector<string> result; for (int i = 0; i < words.size(); i++) { int m = 0;//标记属于哪一行 for (int k = 0; k < 3; k++) if (hashTable[k][words[i][0]]) m = k; for (int j = 0; j < words[i].size(); j++) { if (!hashTable[m][words[i][j]]) break;//出现不属于该行的字符 if (j == words[i].size()-1 && hashTable[m][words[i][j]]) result.push_back(words[i]); } } return result; }
python
查看python solution的时候,我再一次被shock到了。我咋就没想到用正则表达式呢。。在此附上牛人的代码,学习学习。
def findWords(self, words): return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)
([qwertyuiop]|[asdfghjkl]|[zxcvbnm]*) 这段正则是匹配字符的
(?i) 这个是忽略大小写
0 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- LeetCode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- leetcode 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- LeetCode | 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- LeetCode 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- Leetcode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- [leetcode]: 500. Keyboard Row
- leetcode 500. Keyboard Row
- [leetcode] 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 每天一整理-java设计模式之builder模式
- 70%的人离职因领导这4宗罪
- 使用STL模板必须重载的运算符
- Python语言中的协程(生产者-消费者举例)
- 蓝桥杯 基础练习 特殊回文数 JAVA
- [leetcode]: 500. Keyboard Row
- Oracle Mobile Web Application (MWA) 学习小结(1)
- 网络端口大全
- Visio2010建立ER图并直接导出为SQL语句
- 这样读源码,不牛X也难
- 什么时候需要透析
- POJ.1995 Raising Modulo Numbers (快速幂)
- 点gitignore不起作用的解决方法
- 各类资源大全(编程资料,PS等),百度云下载,很全