C++ 中长按姓名

c++server side programmingprogramming

假设有人在键盘上输入姓名。有时,某些按键会被误长按。因此,可能会输入一个或多个多余的字符。因此,我们将获取两个字符串,并检查第二个字符串是否是长按的姓名。如果姓名是"Amit",而第二个字符串是"Ammittt",则表示该姓名是长按的。但"Ammttt"则不是,因为这里没有字符 i。

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

  • let j := 0
  • for i := 0, i < second.size, 将 i 加 1 −
    • if j < actual_name.size 且 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

相关文章