問題(Easy):
Given a List of words, return the words that can be typed using letters ofalphabet
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.
大意:
給出一系列單詞符喝,返回可以只用如下的美式鍵盤中一行字母打印出來的單詞闪彼。
例1:
輸入:["Hello", "Alaska", "Dad", "Peace"]
輸出:["Alaska", "Dad"]注意:
- 你可以使用一個字母多次。
- 你可以假設(shè)輸入只包含字母表的字母协饲。
思路:
既然題目說只包含字母畏腕,那我們就用一個大小為26數(shù)組來記錄每個字母在第幾行课蔬。然后遍歷容器,對于每個字符串郊尝,看看其中每個字母屬于哪一行二跋,這里要注意字母有大小寫之分。為了方便流昏,我們可以用一個變量來保存一個字符串中的字母的行扎即,如果在遍歷字母過程中出現(xiàn)了不一樣的行,那就視為要剔除的字符串况凉,否則就保留谚鄙,這里我們可以用容易的刪除操作,不用創(chuàng)建新容器來保存數(shù)據(jù)刁绒。這樣做的速度最快闷营。
代碼(C++):
class Solution {
public:
vector<string> findWords(vector<string>& words) {
int rows[] = {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};
auto iter = words.begin();
while (iter != words.end()) {
string str = *iter;
int row = 0;
bool pass = true;
for (int i = 0; i <str.length(); i++) {
int index = 0;
if (str[i] - 'a' < 0) index = str[i] - 'A';
else index = str[i] - 'a';
if (row == 0) row = rows[index];
else if (rows[index] != row) {
pass = false;
break;
}
}
if (pass) iter++;
else iter = words.erase(iter, iter+1);
}
return words;
}
};
合集:https://github.com/Cloudox/LeetCode-Record