Leetcode刷题(2)
来源:互联网 发布:netbsd源码 编辑:程序博客网 时间:2024/05/20 17:27
Given a List of words, returnthe words that can be typed using letters of alphabet ononly 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.
Subscribe tosee which companies asked this question.
1. 首先先对vector<string> &words中的string进行遍历
2. 将string分解为单个字母
char *dst = new char[255];
int i;
for(i=0;i <=src.length();i++)
dst[i]=src[i];
dst[i] = '\0';
return dst;
3. 循环,看这个string中的字母是否都在一行,是则输出,不是则不输出
!一定要注意大小写的转换
代码部分
classSolution {
public:
vector<string>findWords(vector<string>& words) {
char l1[10] ={'q','w','e','r','t','y','u','i','o','p'};
char l2[9] ={'a','s','d','f','g','h','j','k','l'};
char l3[7] = {'z','x','c','v','b','n','m'};
vector<string> outputs;
bool a=false,b=false,c=false;
int m=0,n=0,o=0;
for(int it=0;it<words.size();it++) {
string str = words[it];
for(int i=0; i<str.size(); i++){
for(int k=0; k<10; k++) {
if((char)tolower(str[i]) ==l1[k])
++m;
}
}
if(m == str.size()) a = true;
for(int i=0; i<str.size(); i++){
for(int k=0; k<9; k++) {
if((char)tolower(str[i]) ==l2[k])
++n;
}
}
if(n == str.size()) b = true;
for(int i=0; i<str.size(); i++){
for(int k=0; k<7; k++) {
if((char)tolower(str[i]) ==l3[k])
++o;
}
}
if(o == str.size()) c = true;
if(a || b || c)
{outputs.push_back(str);}
m=n=o=0;
a=b=c=false;
}
return outputs;
}
};
参考代码
classSolution {
public:
vector<string>findWords(vector<string>& words) {
unordered_set<char> row1 {'q','w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p'};
unordered_set<char> row2 {'a','s', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
unordered_set<char> row3 { 'z','x', 'c', 'v', 'b' ,'n', 'm'};
vector<unordered_set<char>>rows {row1, row2, row3};
vector<string> validWords;
for(int i=0; i<words.size(); ++i){
int row=0;
for(int k=0; k<3; ++k){
if(rows[k].count((char)tolower(words[i][0])) > 0) row = k;
}
validWords.push_back(words[i]);
for(int j=1; j<words[i].size();++j){
if(rows[row].count((char)tolower(words[i][j])) == 0){
validWords.pop_back();
break;
}
}
}
return validWords;
}
};
总结:参考代码是先将函数定位到某一行,然后进行性判别,如果有某个字母不是在这一行,就移除这个元素。
- LeetCode刷题(2)
- Leetcode刷题(2)
- LeetCode刷题(2)
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- LeetCode 刷题2 (digit sum)
- leetcode刷题(2)
- leetcode刷题-堆栈2
- leetcode刷题(Python)
- LeetCode刷题(1)
- LeetCode刷题(3)
- LeetCode刷题(废弃)
- LeetCode刷题(FizzBuzz)
- Leetcode刷题(1)
- Leetcode刷题(3)
- Leetcode刷题(4)
- Leetcode刷题(5)
- Leetcode刷题(6)
- Leetcode刷题(7)
- 利用python读取带有中文的字符串,和将带有中文的字符串写到txt文件中
- C++常见面试题—内存管理GetMemory()
- bzoj1643
- struts2--2.Action
- 每天一个Linux命令:ping
- Leetcode刷题(2)
- STM32F0开发笔记4: STM32CubeF0固件架构
- Axure7.0安装
- 舞伴问题
- lib和dll文件的区别和联系
- No.50 Pow
- hdu 1241 Oil Deposits 搜索水题,等价于求一个图的连通分量的数目
- Apache服务器简介
- vitualenv中的python package覆盖问题