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.
三、解题思路
- Hash Table
- 官方写的TAG是Hash Table,意思就是查找的时候,先把每一行的字符放到一个map中,然后使用hash的形式来进行查找。这里我用的是string,原理上是差不多的。
- 这道题非常简单,不管效率怎么样,写出一个解题版本来并不难。题目的意思是找出单词,这些单词的每个字母都在键盘上的同一行。首先把每一行的字母分别放到三个字符串中,然后依次遍历word,并记录下第一个字符出现的string编号。如果后面字符和前面的不同,说明该单词不在一行,直接跳过,下一个。如果检测完单词都在同一行,记录到输出数组中即可。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
string line1 = "QWERTYUIOP";
string line2 = "ASDFGHJKL";
string line3 = "ZXCVBNM";
vector<string> ret;
for (string word : words){
int last = -1, cur;
for (char tmp : word){
char ch = toupper(tmp);
if(line1.find(ch) != string::npos){
cur = 1;
}else if(line2.find(ch) != string::npos){
cur = 2;
}else if(line3.find(ch) != string::npos){
cur = 3;
}
if(last == -1){
last = cur;
}else{
if(last != cur) break;
}
}
if(last == cur) ret.push_back(word);
}
return ret;
}
};