题目:
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.
解释:
判断这个单词的所有的字母是否都在键盘的同一行。
记录每一行的字母
把每个单词都变成小写以后数数,如果在某一行出现的次数等于单词的长度则把原始单词加到最终结果上
python代码:
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
line1='qwertyuiop'
line2='asdfghjkl'
line3='zxcvbnm'
result=[]
for word in words:
word_new=word.lower()
_len=len(word)
count=0
line1_count=0
line2_count=0
line3_count=0
for letter in word_new:
if letter in line1:
line1_count+=1
if letter in line2:
line2_count+=1
if letter in line3:
line3_count+=1
if _len in [line1_count,line2_count,line3_count]:
result.append(word)
return result
c++代码:
#include <string>
#include <cctype>
class Solution {
public:
vector<string> findWords(vector<string>& words) {
string line1="qwertyuiop";
string line2="asdfghjkl";
string line3="zxcvbnm";
vector <string> result;
for (auto word:words)
{ int count_line1=0,count_line2=0,count_line3=0;
int _len=word.length();
string new_word=word;
transform(word.begin(),word.end(),new_word.begin(),::tolower);
for(auto letter:new_word)
{
if (line1.find(letter,0)!=string::npos)
count_line1+=1;
if (line2.find(letter,0)!=string::npos)
count_line2+=1;
if (line3.find(letter,0)!=string::npos)
count_line3+=1;
}
vector<int> tmp={count_line1,count_line2,count_line3};
if(find(tmp.begin(),tmp.end(),_len)!=tmp.end())
result.push_back(word);
}
return result;
}
};
总结:
学会使用stl中的transform函数。
transform函数:
作用是将某操作应用于指定范围的每个元素。类似于python中的map函数
transform函数有两个重载版本:
1.transform(first,last,result,op);//first是容器的首迭代器,last为容器的末迭代器,result为存放结果的容器,op为要进行操作的一元函数对象或sturct、class。
2.transform(first1,last1,first2,result,binary_op);//first1是第一个容器的首迭代器,last1为第一个容器的末迭代器,first2为第二个容器的首迭代器,result为存放结果的容器,binary_op为要进行操作的二元函数对象或sturct、class。
tolower()
函数在<cctype>
中。
toupper()
函数在std
中。