Keyboard Row in C++


Given a list of words, we have to find those words that can be typed using letters of the alphabet on only one row's of standard keyboard layout.

So, if the input is like ["hello","world","mom","dad","try","type","tom"], then the output will be ["dad","try","type"]

To solve this, we will follow these steps −

  • Define an array output

  • oneRow := true

  • Define one map charToRowMap, this will take all pairs such that {letter,line}, the letter is the letter present on the keyboard, and line is the line number on the keyboard.

  • for each word in words array −

    • if the word is not empty, then −

      • oneRow := true

      • row := charToRowMap[tolower(word[0])

      • for initialize i := 1, when i < size of word, update (increase i by 1), do −

        • if charToRowMap[tolower(word[i]) is not equal to row, then −

          • oneRow := false

          • Come out from the loop

      • if oneRow is non-zero, then −

        • insert word at the end of the output

  • return output

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<string> findWords(vector<string>& words) {
      vector<string> output;
      bool oneRow = true;
      unordered_map<char, int> charToRowMap{
         { 'q', 1 }, { 'w', 1 }, { 'e', 1 }, { 'r', 1 }, { 't', 1 }, { 'y', 1 }, { 'u', 1 },
{ 'i', 1 }, { 'o', 1 }, { 'p', 1 }, { 'a', 2 }, { 's', 2 }, { 'd', 2 }, { 'f', 2 }, { 'g', 2 }, { 'h', 2 }, { 'j', 2 }, { 'k', 2 }, { 'l', 2 }, { 'z', 3 }, { 'x', 3 }, { 'c', 3 }, { 'v', 3 }, { 'b', 3 }, { 'n', 3 }, { 'm', 3 }
      };
      for (auto word : words)
      if (!word.empty()) {
         oneRow = true;
         int row = charToRowMap[tolower(word[0])];
         for (int i = 1; i < word.length(); i++)
         if (charToRowMap[tolower(word[i])] != row) {
            oneRow = false;
            break;
         }
         if (oneRow)
         output.push_back(word);
      }
      return output;
   }
};
main(){
   Solution ob;
   vector<string> v = {"hello","world","mom","dad","try","type","tom"};
   print_vector(ob.findWords(v));
}

Input

{"hello","world","mom","dad","try","type","tom"}

Output

[dad, try, type, ]

Updated on: 10-Jun-2020

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements