键盘行单词求解

    xiaoxiao2021-04-12  35

    题目来源:

    点击打开链接

    题目描述:

    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.

    我的解决方案:

    class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> ret; for(auto iter=words.begin();iter!=words.end();++iter) { bool right=true; int tmp=findrow((*iter)[0]); for(int i=1;i<iter->size();++i) { if(findrow((*iter)[i])!=tmp) { right=false; break; } } if(right) ret.push_back(*iter); } return ret; } int findrow(char ch) { char row3[20]={"zxcvbnmZXCVBNM"}; char row2[20]={"asdfghjklASDFGHJKL"}; int i=0; while(i<20) { if(row3[i++]==ch) return 3; } while(i>0) { if(row2[--i]==ch) return 2; } return 1; } }; 思考:

    题目很简单,核心是判断一个单词的组成字母是否全部来源于键盘的同一行.所以很容易想到写一个函数来求每个字母在键盘中的行号,然后循环比较这个单词的每个字母的行号,只要有一个不同的,则舍弃.比较麻烦的是怎么得到键盘的行号,最开始只想到了暴力循环和hash散列,后来就觉得反正每行就那么几个字母,用hash好像没啥必要,所以最后还是写了个暴力循环,把每行的字母及其大写都存在一个数组中,由于题目限定输入一定只是英文字母,所以没考虑健壮性,不是第三第二行就一定是第一行(2 3行字母少),直接一个if else就搞定.做完之后看了看别人的做法,大致相同,只是更多的使用了一些二维数组和STL方法之类的东西,代码看着比较简洁.这里摘抄一份wsdgtc911的代码,是我在这道题目下看到的最简洁的C++代码

    class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> res; for(auto str : words) { bool r1 = str.find_first_of("QWERTYUIOPqwertyuiop") == string::npos ? false : true; bool r2 = str.find_first_of("ASDFGHJKLasdfghjkl") == string::npos ? false : true; bool r3 = str.find_first_of("ZXCVBNMzxcvbnm") == string::npos ? false : true; if(r1 + r2 + r3 == 1) res.push_back(str); } return res; } };

    转载请注明原文地址: https://ju.6miu.com/read-667172.html

    最新回复(0)