【简单】500. 键盘行

【题目】
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。
来源:leetcode
链接:https://leetcode-cn.com/problems/keyboard-row/
【示例】
输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
【代码】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :7 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    int ch[27]={1,0,0,1,2,1,1,1,2,1,1,1,0,0,2,2,2,2,1,2,2,0,2,0,2,0};
    vector<string> findWords(vector<string>& words) {
        int base=-1;
        vector<string>rs;
        for(auto x:words){
            int flag=true;
            base=-1;
            for(auto y:x){
                int pos=y-'a';
                if(y>='A'&&y<='Z')
                    pos=y-'A';
                if(base==-1){
                    base=ch[pos];
                }else if(base!=ch[pos]){
                    flag=false;
                    break;
                }
            }
            if(flag)
                rs.push_back(x);
        }
        return rs;
    }
};

【解法二】

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string q{"qwertyuiop"};
        string a{"asdfghjkl"};
        string z{"zxcvbnm"};
        vector<string> ans;    
        for(int i=0;i<words.size();i++){
            int d=0,b=0,c=0,slen=words[i].size();
            for(int j=0;j<words[i].size();j++){
                if(q.find(tolower(words[i][j]))!=string::npos) b++;
                if(a.find(tolower(words[i][j]))!=string::npos) c++;
                if(z.find(tolower(words[i][j]))!=string::npos) d++;
            }
            if(b==slen||c==slen||d==slen) 
                ans.push_back(words[i]);
        }
        return ans;      
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值