题目
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
- the first row consists of the characters “qwertyuiop”,
- the second row consists of the characters “asdfghjkl”, and
- the third row consists of the characters “zxcvbnm”.
Example 1:
Input: words = [“Hello”,“Alaska”,“Dad”,“Peace”]
Output: [“Alaska”,“Dad”]
Example 2:
Input: words = [“omk”]
Output: []
Example 3:
Input: words = [“adsdf”,“sfd”]
Output: [“adsdf”,“sfd”]
Constraints:
- 1 <= words.length <= 20
- 1 <= words[i].length <= 100
- words[i] consists of English letters (both lowercase and uppercase).
代码
class Solution {
public:
vector<string> findWords(vector<string>& words) {
if( words.empty() )
return words;
map<char, int> keyboard;
keyboard.insert(pair<char, int>('Q',1));
keyboard.insert(pair<char, int>('W',1));
keyboard.insert(pair<char, int>('E',1));
keyboard.insert(pair<char, int>('R',1));
keyboard.insert(pair<char, int>('T',1));
keyboard.insert(pair<char, int>('Y',1));
keyboard.insert(pair<char, int>('U',1));
keyboard.insert(pair<char, int>('I',1));
keyboard.insert(pair<char, int>('O',1));
keyboard.insert(pair<char, int>('P',1));
keyboard.insert(pair<char, int>('A',2));
keyboard.insert(pair<char, int>('S',2));
keyboard.insert(pair<char, int>('D',2));
keyboard.insert(pair<char, int>('F',2));
keyboard.insert(pair<char, int>('G',2));
keyboard.insert(pair<char, int>('H',2));
keyboard.insert(pair<char, int>('J',2));
keyboard.insert(pair<char, int>('K',2));
keyboard.insert(pair<char, int>('L',2));
keyboard.insert(pair<char, int>('Z',3));
keyboard.insert(pair<char, int>('X',3));
keyboard.insert(pair<char, int>('C',3));
keyboard.insert(pair<char, int>('V',3));
keyboard.insert(pair<char, int>('B',3));
keyboard.insert(pair<char, int>('N',3));
keyboard.insert(pair<char, int>('M',3));
vector<string> alpha;
while( !words.empty() )
{
string tmp = words.front();
transform(tmp.begin(), tmp.end(), tmp.begin(), (int (*)(int))toupper);
int row = keyboard[tmp[0]], i = 0;
for( ; i < tmp.size(); i ++ )
{
if( row != keyboard[tmp[i]] )
break;
}
if( i == tmp.size() )
alpha.push_back( words.front() );
words.erase(words.begin());
}
return alpha;
}
};
一次AC +1~ ^ __________________________________ ^
该代码实现了一个功能,根据美国键盘的三行布局,筛选出仅使用同一行字母组成的英文单词。给定一个字符串数组`words`,返回可以用单行键盘输入的所有单词。例如,输入`[Hello Alaska Dad Peace]`,输出`[Alaska Dad]`,因为“Hello”和“Peace”中包含的字母分别来自不同行的键盘。代码首先定义了键盘布局,然后遍历每个单词,检查所有字符是否来自同一行,如果是,则将单词添加到结果列表中。
362

被折叠的 条评论
为什么被折叠?



