C ++中的长按名称

假设一个人在键盘上输入了一些名字。有时,某些按钮被误按了很长时间。因此,它可能会键入一个或多个额外字符。因此,我们将使用两个字符串,并检查第二个字符串是否是长按的名称。因此,如果名称是“ Amit”,而第二个字符串是“ Ammittt”,则是长按的名称。但是“ Ammttt”不是,因为此处没有字符i。

为了解决这个问题,我们将遵循以下步骤-

  • 令j:= 0

  • 对于i:= 0,i <second.size,将i增加1-

    • 如果j <Actual_name.size and Actual_name [j] = second [i],则将j增加1

  • 当j = Actual_name.size时返回true,否则返回false

示例

让我们看下面的实现以更好地理解-

#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;
}

输入值

"Amit"
"Ammittt"

输出结果

true