JavaScript 中的子字串組合


我們需要編寫一個 JavaScript 函式,該函式以兩個字串作為第一個和第二個引數。我們稱這兩個字串為 str1 和 str2。此函式應檢查 str2 中是否存在一個子串組合,將這些組合組合在一起會生成 str2。

就子字串組合而言,這意味著我們可以跳過字元,但我們必須保持從 str1 中選擇的字元的順序。

例如 -

如果輸入字串為 -

const str1 = 'desxooajmepwele';
const str2 = 'example';

則輸出應為 -

const output = true;

因為可以透過從 str1 中選取一些字元並保持字元的順序來形成字串 `example`。

示例

程式碼如下 -

 即時演示

const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsString = (str1 = '', str2 = '') => {
   let [foundAt, next] = [0, 0];
   for(const char of str2){
      next = str1.slice(foundAt).indexOf(char);
      if (next === - 1){
         return false;
      };
      foundAt += next + 1;
   };
   return true;
};
console.log(containsString(str1, str2));

輸出

控制檯中的輸出為 -

true

更新於: 24-02-2021

179 次瀏覽

開啟您的 職業生涯

透過完成本課程獲得認證

開始
廣告