-->

Saturday, February 4, 2017

[LeetCode] 500. Keyboard Row

https://leetcode.com/contest/leetcode-weekly-contest-18a/problems/keyboard-row/

Solution:
may use a hashmap to label the letters in the same row. Also need to pay attention to the upper or lower letters.

Code:
  1. class Solution {
  2. public:
  3.     vector<string> findWords(vector<string>& words) {
  4.         vector<string> res;
  5.         string v1="qwertyuiop", v2="asdfghjkl", v3="zxcvbnm";
  6.         unordered_map<char, int> m;
  7.         for(auto a:v1) m[a]=0;
  8.         for(auto a:v2) m[a]=1;
  9.         for(auto a:v3) m[a]=2;
  10.         for(auto a:words){
  11.             if(a.size()){
  12.                 int t = -1;
  13.                 if(m.find(a.front())!=m.end()) t = m[a.front()];
  14.                 else t = m[(a.front()+32)];
  15.                 bool flag = true;
  16.                 for(auto b:a){
  17.                     if((m.find(b)!=m.end()&&m[b]==t) || (m.find(b+32)!=m.end()&&m[b+32]==t)) continue;
  18.                     else{
  19.                         flag = false;
  20.                         break;
  21.                     }
  22.                 }
  23.                 if(flag) res.push_back(a);
  24.             }
  25.         }
  26.         return res;
  27.     }
  28. };

No comments :

Post a Comment