leetcode.500.Keyboard Row

Description

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 1:

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.

sln

  1. 创建一个数字,记录26个字符分别属于哪一行(一个由0,1,2组成的数组)
  2. 遍历每个单词,可以用O(1)的时间确定字母属于哪一行,那么可以用O(m)的时间确定整个单词是否可以用键盘的其中一行打出来,其中m为字符串长度
  3. 用O(n * m)的时间可以完成整个任务,c++实现如下
class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> ret;
        int belongTo[] = {1, 2, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 2, 0, 2};
        for (vector<string>::iterator it = words.begin(); it != words.end(); it++) {
            string word = *it;
            int group = -1;
            bool flag = true;
            for (int i = 0; i < word.length(); i++) {
                int cgroup = belongTo[toLower(word[i]) - 'a'];
                if (group != -1 && group != cgroup) {
                    flag = false;
                    break;
                } else {
                    group = cgroup;
                }
            }
            if (flag) {
                ret.push_back(word);
            }
        }
        return ret;
    }
private:
    char toLower(char a) {
        if (a >= 'A' && a <= 'Z') {
            return 'a' + (a - 'A');
        }
        return a;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值