Long Pressed Name in C++


Suppose a man is typing some name on keyboard. Sometimes some buttons are long-pressed by mistake. So it may type one or more extra character. So we will take two strings, and check whether the second string is long-pressed name or not. So if the name is “Amit”, and second string is “Ammittt” is longpressed name. But “Ammttt” is not, because character i is not present here.

To solve this, we will follow these steps −

  • let j := 0
  • for i := 0, i < second.size, increase i by 1 −
    • if j < actual_name.size and actual_name[j] = second[i], thenincrease j by 1
  • return true when j = actual_name.size, otherwise false

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isLongPressedName(string name, string typed) {
      int j = 0;
      for(int i = 0; i < typed.size(); i++){
         if(j < name.size() && name[j] == typed[i])j++;
      }
      return j == name.size();
   }
};
main(){
   Solution ob;
   string res = ob.isLongPressedName("Amit", "Ammittt") ? "true" :
   "false";
      cout << res;
}

Input

"Amit"
"Ammittt"

Output

true

Updated on: 28-Apr-2020

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements