[LeetCode] 500.Keyboard Row

[LeetCode] 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.

这里写图片描述

Example:

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.

解题思路

这道题是一道比较形象比较容易理解的题,题目的意思就是给你一个vector,里面有一些只由字母组成的字符串,如果某个字符串不是由键盘上同一行的字母组成的则删除它。最后返回得到的新的vector。
做法应该是有很多种的,我的方法看起来比较麻烦,但比较容易理解。就是将26个字母按其在键盘所在的行数分为三类,用一个temp数组来保存它所处行的信息。之后将每一个字符串拿出来考虑,在考虑是否在同一行时还要注意大小写的区分,按我的做法就必须分开两种情况来判断。记录下字符串中每一行字母的个数,只有一行个数不为0就满足条件,留下来,否则就用erase()函数删除。使用我的方法要注意边界的选择和a, b, c三个计数器的清零。

实验代码

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        int temp[26] = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3};
        int a = 0, b = 0, c = 0;
        for (int i = 0; i < words.size(); i++) {
            string ss = words[i];
            int l = ss.length();
            for (int j = 0; j < l; j++) {
                if (ss[j] >= 65 && ss[j] <= 90) {
                    if (temp[ss[j]-'A'] == 1) a++;
                    else if (temp[ss[j]-'A'] == 2) b++;
                    else c++;
                } else {
                    if (temp[ss[j]-'a'] == 1) a++;
                    else if (temp[ss[j]-'a'] == 2) b++;
                    else c++;
                }
            }
            if ((a != 0 && b == 0 && c == 0) || (a == 0 && b != 0 && c == 0) || (a == 0 && b == 0 && c != 0)) {
                a = 0;
                b = 0;
                c = 0;
                continue;
            } else {
                words.erase(words.begin()+i);
                i--;
                a = 0;
                b = 0;
                c = 0;
            }
        }
        return words;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值