leetcode 500. Keyboard Row(easy)

来源:互联网 发布:怎样在淘宝买微博小号 编辑:程序博客网 时间:2024/06/05 18:28

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.
题目的要求是找出在键盘一行可以输出的单词,那么采用空间换时间的方法,以每个大写字母为key,层数为值存放键盘信息。这里用了map结构。

class Solution {public:         bool isOneRow(string s,map<char,int> &temp)     {         int len = s.length();         int flag = 0;         for(int i = 0;i<len;i++)         {             if(i == 0)                 flag = temp[toupper(s[i])];             else             {                 int m = temp[toupper(s[i])];                 if(flag != m)                    return false;                          }         }         return true;     }    vector<string> findWords(vector<string>& words) {         map<char,int> temp;         temp['A'] = 2;         temp['S'] = 2;         temp['D'] = 2;         temp['F'] = 2;         temp['G'] = 2;         temp['H'] = 2;         temp['J'] = 2;         temp['K'] = 2;         temp['L'] = 2;         temp['Q'] = 1;         temp['W'] = 1;         temp['E'] = 1;         temp['R'] = 1;         temp['T'] = 1;         temp['Y'] = 1;         temp['U'] = 1;         temp['I'] = 1;         temp['O'] = 1;         temp['P'] = 1;         temp['Z'] = 3;         temp['X'] = 3;         temp['C'] = 3;         temp['V'] = 3;         temp['B'] = 3;         temp['N'] = 3;         temp['M'] = 3;        vector<string> result;        vector<string>::iterator iter = words.begin();        for(;iter != words.end();++iter)        {            if(isOneRow(*iter,temp))                 result.push_back(*iter);                                }        return result;    }};


0 0