感觉还蛮尴尬的,学 cpp 也有一段时间了,居然不知道 for 还有这样的使用。
不说了,贴题目和代码。
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.
American keyboard
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.
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> outStr;
string qwe = "qwertyuiopQWERTYUIOP";
string asd = "asdfghjklASDFGHJKL";
string zxc = "zxcvbnmZXCVBNM";
for (auto &word:words)
{
bool f1 = true;
bool f2 = true;
bool f3 = true;
for (auto &ch:word)
{
for (int i = 0; i < qwe.length(); i++)
{
if (ch == qwe[i])
{
f1 = false;
break;
}
}
for (int i = 0; i < asd.length(); i++)
{
if (ch == asd[i])
{
f2 = false;
break;
}
}
for (int i = 0; i < zxc.length(); i++)
{
if (ch == zxc[i])
{
f3 = false;
break;
}
}
}
if(f1 == true && f2 == true && f3 == false) outStr.push_back(word);
if(f1 == false && f2 == true && f3 == true) outStr.push_back(word);
if(f1 == true && f2 == false && f3 == true) outStr.push_back(word);
}
return outStr;
}
};
写 cpp 到现在,还比较抵触容器,还是比较习惯 c 里面的数组的概念,但数组也很不好用。
今天才知道 for (auto &word:words)
还可以这样使用 for 的,那不是美滋滋吗。
记住!