2021-10-31 LeetCode 500.键盘行

LeetCode 500.键盘行

原题链接 ==10.31==

题目描述:

给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。

美式键盘 中:

  • 第一行由字符 "qwertyuiop" 组成。
  • 第二行由字符 "asdfghjkl" 组成。
  • 第三行由字符 "zxcvbnm" 组成。

代码:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string line[3] = {
            "qwertyuiop",
            "asdfghjkl",
            "zxcvbnm"
        };
        
        vector<string> res;
        unordered_map<char, int> hash;
        
        for (int i = 0; i < 3; i ++ ){
            for (auto& c : line[i])
                hash[c] = i; 
        }
        
        for (auto word : words){
            set<int> S;
            for (auto c : word){
                S.insert(hash[tolower(c)]);
            }
            if (S.size() == 1) res.push_back(word);
        }
        return res;
        
    }
};
  1. 使用 unordered_map<char, int> 存储每个字母出现在哪一行。
  2. 输入的字符串中存在大写字母,在查找存在哪一行时需要转换成小写,使用 tolower() 函数
  3. 利用 set 的特性存储每个行的字母出现的次数
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。 美式键...
    e8889d737099阅读 209评论 0 0
  • 键盘行 题目描述:给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。示例说...
    醉舞经阁半卷书阅读 205评论 0 3
  • 500. 键盘行 给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。 示例: 注意...
    TheKey_阅读 102评论 0 1
  • 问题(Easy): Given a List of words, return the words that ca...
    Cloudox_阅读 284评论 0 0
  • 来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/keyboa...
    xialu阅读 172评论 0 0