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


翻译:

给定一组单词,只返回可在美式键盘的一行上使用字母表输入的文字,如下图所示。



American keyboard


例子 1:

输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]

注意:

  1. 你可以多次使用键盘中的字符。
  2. 您可以认为输入的字符串只包含字母表的字母。


思路:

将键盘中的三行字符分别存储到三个set集合中,然后,对于一个字符串的每一个字符,分别判断它在三行中出现的个数,如果出现,则将行标识置为1,否则,保持初始的行标识0,最后通过将3行的行标识相加用以判断字符串中的字符是否只来自于同一行。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <set>
#include <string>
using namespace std;

class Solution {
public:
	vector<string> findWords(vector<string>& words) {
		set<char> row1 = { 'q', 'w','e','r','t','y','u','i','o','p'};
		set<char> row2 = {'a','s','d','f','g','h','j','k','l'};
		set<char> row3 = {'z','x','c','v','b','n','m'};
		vector<string> res;
		for (string word:words) {
			int one = 0, two = 0, three = 0;
			for (char c : word) {
				//if (c < 'a') c += 32;
				if (row1.count(tolower(c))) one = 1; //用来判断set中出现字符c的个数
				if (row2.count(tolower(c))) two = 1;
				if (row3.count(tolower(c))) three = 1;
				if (one + two + three > 1) break;
			}
			if (one + two + three == 1)
				res.push_back(word);
		}
		return res;
	}
};

int main()
{
	Solution s;
	vector<string> words = { "Hello","Alaska","Dad","Peace" };
	vector<string> result;
	result = s.findWords(words);
	for (int i = 0; i < result.size(); i++) {
		cout << result[i] << " ";
	}
    return 0;
}

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值