題目來源:
題目描述:
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.
我的解決方案:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> ret;
for(auto iter=words.begin();iter!=words.end();++iter)
{
bool right=true;
int tmp=findrow((*iter)[0]);
for(int i=1;i<iter->size();++i)
{
if(findrow((*iter)[i])!=tmp)
{
right=false;
break;
}
}
if(right)
ret.push_back(*iter);
}
return ret;
}
int findrow(char ch)
{
char row3[20]={"zxcvbnmZXCVBNM"};
char row2[20]={"asdfghjklASDFGHJKL"};
int i=0;
while(i<20)
{
if(row3[i++]==ch)
return 3;
}
while(i>0)
{
if(row2[--i]==ch)
return 2;
}
return 1;
}
};
思考:
題目很簡單,核心是判斷一個單詞的組成字母是否全部來源於鍵盤的同一行.所以很容易想到寫一個函數來求每個字母在鍵盤中的行號,然後循環比較這個單詞的每個字母的行號,只要有一個不同的,則捨棄.比較麻煩的是怎麼得到鍵盤的行號,最開始只想到了暴力循環和hash散列,後來就覺得反正每行就那麼幾個字母,用hash好像沒啥必要,所以最後還是寫了個暴力循環,把每行的字母及其大寫都存在一個數組中,由於題目限定輸入一定只是英文字母,所以沒考慮健壯性,不是第三第二行就一定是第一行(2 3行字母少),直接一個if else就搞定.做完之後看了看別人的做法,大致相同,只是更多的使用了一些二維數組和STL方法之類的東西,代碼看着比較簡潔.這裏摘抄一份wsdgtc911的代碼,是我在這道題目下看到的最簡潔的C++代碼
class Solution {
public:
vector<string> findWords(vector<string>& words)
{
vector<string> res;
for(auto str : words)
{
bool r1 = str.find_first_of("QWERTYUIOPqwertyuiop") == string::npos ? false : true;
bool r2 = str.find_first_of("ASDFGHJKLasdfghjkl") == string::npos ? false : true;
bool r3 = str.find_first_of("ZXCVBNMzxcvbnm") == string::npos ? false : true;
if(r1 + r2 + r3 == 1)
res.push_back(str);
}
return res;
}
};