leetcode 500. Keyboard Row

来源:互联网 发布:cad截图软件 编辑:程序博客网 时间:2024/06/05 11:10

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:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.

起初读了好几次都没搞清楚题意,后来才明白,题意是这样的:给出n个字符串,从而判断每个字符串中的字符石头来自美式键盘上的同一行,若来自同一行,返回该string。过程将键盘上的每行字符存储到相应的vector或者数组中,然后循环Input中的每个string,并且循环string中的每个char,从而进行比较。

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;class Solution {public:    vector<string> findWords(vector<string>& words)     {        vector<string> res;        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' };        for (string word : words)        {            bool d1 = true, d2 = true, d3 = true;            for (char c : word)            {                if (d1 == true)                {                    if (row1.find(tolower(c)) == row1.end())                        d1 = false;                }                if (d2 == true)                {                    if (row2.find(tolower(c)) == row2.end())                        d2 = false;                }                if (d3 == true)                {                    if (row3.find(tolower(c)) == row3.end())                        d3 = false;                }            }            if (d1 || d2 || d3)                res.push_back(word);        }        return res;    }};