Problem Statement
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.
Thinking
题目的意思是给出一个vector,如果里面的单词所有的字母不全在键盘字母区的同一行上就删除。我的代码是如果在同一行上就把他放到另一个vector里面,尝试过直接从vector里删除,但是删除以后指针会自动往后移动一位,然后循环再后移一位,但是这样很容易溢出,所以直接用了一个新的vector。
Solution
class Solution {
public:
vector<string> findWords(vector<string>& words) {
string line1("qwertyuiopQWERTYUIOP");
string line2("asdfghjklASDFGHJKL");
string line3("zxcvbnmZXCVBNM");
vector<string> fin_words;
int line_num = 1,num = 0,judge = 0,buff = 0;
vector<string>::iterator iter;
string::iterator iter2;
for(iter = words.begin(); iter!=words.end();iter++)
{
int i = 0;
string temp = *iter;
//temp[0] = tolower(temp[0]);
for(iter2 = temp.begin(); iter2!=temp.end(); iter2++)
{
i++;
if(i == 1)
{
if(line1.find(*iter2) != string::npos)
num = 1;
else if(line2.find(*iter2) != string::npos)
num = 2;
else if(line3.find(*iter2) != string::npos)
num = 3;
}
else
{
if(num == 1)
if(line1.find(*iter2) != string::npos)
buff++;
else if(num == 2)
if(line2.find(*iter2) != string::npos)
buff++;
else if(num == 3)
if(line3.find(*iter2) != string::npos)
buff++;
}
}
if(buff + 1 == temp.size())
fin_words.push_back(*iter);
buff = 0;
}
return fin_words;
}
};