给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
示例:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
思路:
遍历每个单词,逐字母判断是否在同一行,如果不在就退出该单词匹配
性能分析:
时间复杂度O(N * maxBit(word))
空间复杂度为O(1)
具体代码:
//打表,记录字母所在行
// a b c d e f g h i j k l m n o p q r s t u v w x y z
int key_value[30] = {2, 3, 3, 2, 1,
2, 2, 2, 1, 2,
2, 2, 3, 3, 1,
1, 1, 1, 2, 1,
1, 3, 1, 3, 1, 3};
//翻译函数,将字符所在行返回
int trans(char c){
if(c >= 'a' && c <= 'z'){
return key_value[c - 'a'];
}
return key_value[c - 'A'];
}
//需求函数
vector<string> findWords(vector<string>& words) {
vector<string> res;
//遍历所有单词
for(int i = 0; i < words.size(); i++){
//type=单词首字母所在行号
int type = trans(words[i][0]);
int j;
//遍历单词所有字母,判断是否均为type
for(j = 1; j < words[i].size(); j++){
if(trans(words[i][j]) != type) break;
}
//判断是否整个单词遍历完成
if(j == words[i].size()){
res.push_back(words[i]);
}
}
return res;
}
网友评论