[LeetCode] 500.Keyboard Row
- 题目描述
- 解题思路
- 实验代码
题目描述
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:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
Note:
1. You may use one character in the keyboard more than once.
2. You may assume the input string will only contain letters of alphabet.
解题思路
这道题是一道比较形象比较容易理解的题,题目的意思就是给你一个vector,里面有一些只由字母组成的字符串,如果某个字符串不是由键盘上同一行的字母组成的则删除它。最后返回得到的新的vector。
做法应该是有很多种的,我的方法看起来比较麻烦,但比较容易理解。就是将26个字母按其在键盘所在的行数分为三类,用一个temp数组来保存它所处行的信息。之后将每一个字符串拿出来考虑,在考虑是否在同一行时还要注意大小写的区分,按我的做法就必须分开两种情况来判断。记录下字符串中每一行字母的个数,只有一行个数不为0就满足条件,留下来,否则就用erase()函数删除。使用我的方法要注意边界的选择和a, b, c三个计数器的清零。
实验代码
class Solution {
public:
vector<string> findWords(vector<string>& words) {
int temp[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};
int a = 0, b = 0, c = 0;
for (int i = 0; i < words.size(); i++) {
string ss = words[i];
int l = ss.length();
for (int j = 0; j < l; j++) {
if (ss[j] >= 65 && ss[j] <= 90) {
if (temp[ss[j]-'A'] == 1) a++;
else if (temp[ss[j]-'A'] == 2) b++;
else c++;
} else {
if (temp[ss[j]-'a'] == 1) a++;
else if (temp[ss[j]-'a'] == 2) b++;
else c++;
}
}
if ((a != 0 && b == 0 && c == 0) || (a == 0 && b != 0 && c == 0) || (a == 0 && b == 0 && c != 0)) {
a = 0;
b = 0;
c = 0;
continue;
} else {
words.erase(words.begin()+i);
i--;
a = 0;
b = 0;
c = 0;
}
}
return words;
}
};