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.
题目要求:给定一个string数组,遍历数组中的string字符串,如果该字符串的每一个字母都在键盘上的同一行,则将其保留,否则删除该string。
我的思路是用一个数组来记录每一个字母在哪一行,从0-25分别记录a/A-z/Z这26个字母的所在行数,所以声明数组如下:
int mark[26] = {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};
当我遍历每个字符串中的每个字符时,我利用ASCii码来确定该字母在数组中的索引,然后将前后两个字母比较,判断是否在同一行:
for (int j = 1; j < words[i].size(); j++) {
int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A');
int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A');
if (mark[index1] != mark[index2]) {
isOneRow = false;
break;
}
}
因为字符串中的字母有大小写之分,所以确定索引的时候要进行判断。
完整的代码如下:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
int mark[26] = {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};
vector<string> result;
for (int i = 0; i < words.size(); i++) {
bool isOneRow = true;
for (int j = 1; j < words[i].size(); j++) {
int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A');
int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A');
if (mark[index1] != mark[index2]) {
isOneRow = false;
break;
}
}
if (isOneRow)
result.push_back(words[i]);
}
return result;
}
};