zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode笔记:500. Keyboard Row

2023-03-15 23:24:07 时间

问题(Easy):

Given a List of words, return the words that can be typed using letters ofalphabet on only one row's of American keyboard like the image below.

Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

大意:

给出一系列单词,返回可以只用如下的美式键盘中一行字母打印出来的单词。

例1: 输入:["Hello", "Alaska", "Dad", "Peace"] 输出:["Alaska", "Dad"] 注意:

  1. 你可以使用一个字母多次。
  2. 你可以假设输入只包含字母表的字母。

思路:

既然题目说只包含字母,那我们就用一个大小为26数组来记录每个字母在第几行。然后遍历容器,对于每个字符串,看看其中每个字母属于哪一行,这里要注意字母有大小写之分。为了方便,我们可以用一个变量来保存一个字符串中的字母的行,如果在遍历字母过程中出现了不一样的行,那就视为要剔除的字符串,否则就保留,这里我们可以用容易的删除操作,不用创建新容器来保存数据。这样做的速度最快。

代码(C++):

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        int rows[] = {2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3};
        auto iter = words.begin();
        while (iter != words.end()) {
            string str = *iter;
            int row = 0;
            bool pass = true;
            for (int i = 0; i <str.length(); i++) {
                int index = 0;
                if (str[i] - 'a' < 0) index = str[i] - 'A';
                else index = str[i] - 'a';
                
                if (row == 0) row = rows[index];
                else if (rows[index] != row) {
                    pass = false;
                    break;
                }
            }
            if (pass) iter++;
            else iter = words.erase(iter, iter+1);
        }
        return words;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record