题目:
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.
翻译:
给定一组单词,只返回可在美式键盘的一行上使用字母表输入的文字,如下图所示。
例子 1:
输入: ["Hello", "Alaska", "Dad", "Peace"] 输出: ["Alaska", "Dad"]
注意:
- 你可以多次使用键盘中的字符。
您可以认为输入的字符串只包含字母表的字母。
思路:
将键盘中的三行字符分别存储到三个set集合中,然后,对于一个字符串的每一个字符,分别判断它在三行中出现的个数,如果出现,则将行标识置为1,否则,保持初始的行标识0,最后通过将3行的行标识相加用以判断字符串中的字符是否只来自于同一行。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <set>
#include <string>
using namespace std;
class Solution {
public:
vector<string> findWords(vector<string>& words) {
set<char> row1 = { 'q', 'w','e','r','t','y','u','i','o','p'};
set<char> row2 = {'a','s','d','f','g','h','j','k','l'};
set<char> row3 = {'z','x','c','v','b','n','m'};
vector<string> res;
for (string word:words) {
int one = 0, two = 0, three = 0;
for (char c : word) {
//if (c < 'a') c += 32;
if (row1.count(tolower(c))) one = 1; //用来判断set中出现字符c的个数
if (row2.count(tolower(c))) two = 1;
if (row3.count(tolower(c))) three = 1;
if (one + two + three > 1) break;
}
if (one + two + three == 1)
res.push_back(word);
}
return res;
}
};
int main()
{
Solution s;
vector<string> words = { "Hello","Alaska","Dad","Peace" };
vector<string> result;
result = s.findWords(words);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
return 0;
}
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.