LeetCode 500. Keyboard Row-Java

来源:互联网 发布:事业单位网络教育学历 编辑:程序博客网 时间:2024/06/06 06:42

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.

Problem: 
给一个数组,判断给定的单词中的每个字母能否都在美式键盘的同一行? 
Solution: 

创建三个数组,然后对每个单词中的字母查找是否在同一个数组当中。 
note: 
在集合中查找是否存在最高效的办法是使用hash表,而不是并查集。

class Solution {public:    vector<string> findWords(vector<string>& words) {        unordered_set<char> row1 {'q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p'};        unordered_set<char> row2 {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};        unordered_set<char> row3 { 'z', 'x', 'c', 'v', 'b' ,'n', 'm'};        vector<unordered_set<char>> rows {row1, row2, row3};        vector<string> validWords;        for(int i=0; i<words.size(); ++i){            int row=0;            for(int k=0; k<3; ++k){                if(rows[k].count((char)tolower(words[i][0])) > 0) row = k;            }            for(int j=0; j<words[i].size(); ++j){                if(rows[row].count((char)tolower(words[i][j])) == 0)                    break;                if(j == words[i].size()-1)                    validWords.push_back(words[i]);            }        }        return validWords;    }};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26


0 0
原创粉丝点击