Every day a leetcode
题目来源:500. 键盘行
解法1:遍历
我们使用3个哈希表记录键盘每行的字母。
遍历每个words中的字符串word,利用哈希表来判断字符串word的所有字符c是否在同一个哈希表内,若是则说明word是可以使用在美式键盘同一行的字母打印出来的单词;否则,不是。
注意:word中有大写字母,在哈希表中查找时应该先转换为小写字母。
代码:
/*
* @lc app=leetcode.cn id=500 lang=cpp
*
* [500] 键盘行
*/
// @lc code=start
class Solution
{
public:
vector<string> findWords(vector<string> &words)
{
vector<string> ans;
string s[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
// for (string word : s)
// cout << word << endl;
unordered_set<char> check[3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < s[i].size(); j++)
check[i].insert(s[i][j]);
// for (int i = 0; i < 3; i++)
// {
// for (auto it = check[i].begin(); it != check[i].end(); it++)
// cout << *it << " ";
// cout << endl;
// }
for (string word : words)
{
int i;
bool judge = true;
for (i = 0; i < 3; i++)
if (check[i].count(tolower(word[0])))
break;
for (char c : word)
if (!check[i].count(tolower(c)))
{
judge = false;
break;
}
if (judge == true)
ans.push_back(word);
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(L),其中 L 表示 words 中所有字符串的长度之和。
空间复杂度:O(|Σ|),其中 |Σ| 表示英文字母的个数,在本题中英文字母的个数为 26。注意返回值不计入空间复杂度。
解法2:遍历
我们为每一个英文字母标记其对应键盘上的行号,然后检测字符串中所有字符对应的行号是否相同。
我们可以预处理计算出每个字符对应的行号。
遍历字符串时,统一将大写字母转化为小写字母方便计算。
代码:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> ans;
string rowIdx = "12210111011122000010020202";
for (auto & word : words) {
bool isValid = true;
char idx = rowIdx[tolower(word[0]) - 'a'];
for (int i = 1; i < word.size(); ++i) {
if(rowIdx[tolower(word[i]) - 'a'] != idx) {
isValid = false;
break;
}
}
if (isValid) {
ans.emplace_back(word);
}
}
return ans;
}
};
结果:
复杂度分析:
时间复杂度:O(L),其中 L 表示 words 中所有字符串的长度之和。
空间复杂度:O(|Σ|),其中 |Σ| 表示英文字母的个数,在本题中英文字母的个数为 26。注意返回值不计入空间复杂度。