题目
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~ ^ __________________________________ ^