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:
class Solution {
public:
static vector findWords(vector& words) {
if (0 ==init_flag)
{
//!初始化的工作其实可以放在开始findWords之前
init_dictionary ();
}
int pre_flag = -1;
for (int i = 0; i < words.size(); )
{
for (int j = 0; j < words[i].size(); ++ j)
{
char ch = words[i][j] >= 'a' ? words[i][j] - 'a' + 'A' : words[i][j];
if (pre_flag == -1)
{
pre_flag = find_dictionary(ch);
continue;
}
else if (pre_flag == find_dictionary(ch))
{
continue;
}
else //pre_flag != find_dictionary(ch)
{
words.erase(words.begin()+i);
pre_flag = -1;
break;
}
}//for
if (-1 != pre_flag)
{
++i;
pre_flag = -1;
}
}//for
return words;
}
static void init_dictionary ()
{
string a = "QWERTYUIOP";
string b = "ASDFGHJKL";
string c = "ZXCVBNM";
for (int i = 0; i < a.size(); ++i)
{
dict[a[i]] = 0;
}
for (int i = 0; i < b.size(); ++i)
{
dict[b[i]] = 1;
}
for (int i = 0; i < c.size(); ++i)
{
dict[c[i]] = 2;
}
init_flag = 1;
}
static int find_dictionary (char ch)
{
//!这里因为输入都是正常,所以没有考虑迭代器是end,实际要考虑的
return (dict.find(ch))->second;
}
static map dict;
static int init_flag;
};
int Solution::init_flag = 0;
map Solution::dict;