500. Keyboard Row*

500. Keyboard Row*

https://leetcode.com/problems/keyboard-row/

题目描述

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:

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.

C++ 实现 1

判断每个 word 是否在同一行.

class Solution {
private:
    vector<string> keyboard{"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"};
    bool stringInRow(unordered_set<char> &row, string &s) {
        for (auto &c : s)
            if (row.find(c) == row.end())
                return false;
        return true;
    }
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> res;
        if (words.empty())
            return res;
        unordered_map<int, unordered_set<char>> row;
        for (int i = 0; i < 3; ++i) {
            row[i+1].insert(keyboard[i].begin(), keyboard[i].end());
            // 增加小写的结果
            std::transform(keyboard[i].begin(), keyboard[i].end(), keyboard[i].begin(), ::tolower);
            row[i+1].insert(keyboard[i].begin(), keyboard[i].end());
        }

        for (auto &word : words) {
            bool i = stringInRow(row[1], word) || stringInRow(row[2], word) || stringInRow(row[3], word);
            if (i)
                res.push_back(word);
        }
        return res;
    }
};

C++ 实现 2

另外一种思路, 判断每个 char 所在的行数, 如果一个 word 中前后两个 char 所在的行数不同, 则返回 false.

class Solution {
private:
    int findRow(const char &c) {
        string row1 = "QWERTYUIOP", row2 = "ASDFGHJKL", row3 = "ZXCVBNM";
        unordered_set<char> set1(row1.begin(), row1.end()),
                            set2(row2.begin(), row2.end()),
                            set3(row3.begin(), row3.end());
        
        auto C = std::toupper(c);
        if (set1.count(C)) return 1;
        else if (set2.count(C)) return 2;
        return 3;
    }
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> res;
        for (auto &word : words) {
            int prev = 0;
            bool fit = true;
            for (auto &c : word) {
                auto cur = findRow(c);
                if (!prev) prev = cur;
                else if (prev != cur) {
                    fit = false;
                    break;
                }
            }
            if (fit) res.push_back(word);
        }
        return res;
    }
};
发布了394 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104766771