前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T49-键盘行

【leetcode刷题】T49-键盘行

作者头像
木又AI帮
修改2019-07-18 10:05:08
3760
修改2019-07-18 10:05:08
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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:

代码语言:javascript
复制
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.

【中文题目】

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

示例:

代码语言:javascript
复制
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]

注意:

  1. 你可以重复使用键盘上同一字符。
  2. 你可以假设输入的字符串将只包含字母。

【思路】

使用set储存每一行的字母,判断单词的每个字母是否在同一个set中,或者,将单词转换为set,判断其与键盘每一行字母set的差集是否为空集。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        alpha_set = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]
        res = []
        for word in words:
            tmp_set = set(word.lower())
            for s in alpha_set:
                if len(tmp_set - s) == :
                    res.append(word)
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<set<char>> alpha_set;
        alpha_set.push_back(set<char> {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'});
        alpha_set.push_back(set<char> {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'});
        alpha_set.push_back(set<char> {'z', 'x', 'c', 'v', 'b', 'n', 'm'});
        vector<string> res;
        for(int i=; i<words.size(); i++){
            for(int j=; j<alpha_set.size(); j++){
                int k = ;
                for(k=; k<words[i].length(); k++){
                    char w = words[i][k];
                    if(w < )
                        w += ;
                    if(alpha_set[j].find(w) == alpha_set[j].end())
                        break;
                }
                if(k == words[i].length())
                    res.push_back(words[i]);
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档