500. Keyboard Row

本文介绍了一种算法,用于从给定的字符串数组中筛选出所有字母均可使用美国键盘单行输入的单词。通过标记每个字母所在的键盘行,并检查每个单词的一致性,实现了高效的过滤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


题目要求:给定一个string数组,遍历数组中的string字符串,如果该字符串的每一个字母都在键盘上的同一行,则将其保留,否则删除该string。

我的思路是用一个数组来记录每一个字母在哪一行,从0-25分别记录a/A-z/Z这26个字母的所在行数,所以声明数组如下:
int mark[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};

当我遍历每个字符串中的每个字符时,我利用ASCii码来确定该字母在数组中的索引,然后将前后两个字母比较,判断是否在同一行:
for (int j = 1; j < words[i].size(); j++) {
                int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A');
                int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A');
                if (mark[index1] != mark[index2]) {
                    isOneRow = false;
                    break;
                }
            }

因为字符串中的字母有大小写之分,所以确定索引的时候要进行判断。
完整的代码如下:
class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        int mark[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};
        vector<string> result;
        for (int i = 0; i < words.size(); i++) {
            bool isOneRow = true;
            for (int j = 1; j < words[i].size(); j++) {
                int index1 = (words[i][j-1] - 'a' >= 0) ? (words[i][j-1] - 'a') : (words[i][j-1] - 'A');
                int index2 = (words[i][j] - 'a' >= 0) ? (words[i][j] - 'a') : (words[i][j] - 'A');
                if (mark[index1] != mark[index2]) {
                    isOneRow = false;
                    break;
                }
            }
            if (isOneRow)
                result.push_back(words[i]);
        }
        
        return result;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值