在 C++ 中長按名稱


假設一個人正在鍵盤上打字。有時,會錯誤地長按某些按鈕。因此,它可能會輸入一個或多個額外的字元。因此,我們將獲取兩個字串,並檢查第二個字串是否為長按名稱。因此,如果名稱為“Amit”,第二個字串“Ammittt”是長按名稱。但“Ammttt”不是,因為這裡沒有字元 i。

為解決這個問題,我們將遵循以下步驟:

  • 設 j := 0
  • 對於 i := 0,i < second.size,i 加 1
    • 如果 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

更新於:2020 年 4 月 28 日

247 次瀏覽

職業啟航

完成課程獲得認證

開始
廣告
© . All rights reserved.