500. 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.


American keyboard


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:

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        if(words.size()==0){return words;}
        string a[3]={"qwertyuiop","asdfghjkl","zxcvbnm"};
        map<char,int> keyboard;
        int i=0;
        for(string st:a){
            for(char ch:st){
                keyboard[ch]=i;
            }
            i++;
        }
        vector<string> result;
        for(string ss:words){
            bool flag=true;
            char head=ss[0];
            if(head<'a'){head=ss[0]+32;}
            for(char ch:ss){
                if(ch<'a'){ch=ch+32;}
                if(keyboard[head]!=keyboard[ch]){
                    flag=false;
                    break;
                }
            }
            if(flag){result.push_back(ss);}
        }
        return result;
    }
};
代码2:
class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> keyb,res;
        map<char,int> m;
        keyb.push_back("qwertyuio");
        keyb.push_back("asdfghjkl");
        keyb.push_back("zxcvbnm");
        for(int i=0;i<3;i++){
            for(char ch:keyb[i]){m[ch]=i;}
        }
        for(string word:words){
            set<int> temp;
            for(char ch:word){
                if(isupper(ch)){ch=tolower(ch);}
                temp.insert(m[ch]);
            }
            if(temp.size()==1){res.push_back(word);}
    }
        return res;
    }
};
isupper/islower/toupper/tolower->头文件<cctype>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值