JavaScript 匹配字串中的萬用字元


我們被要求編寫一個 JavaScript 函式,該函式接收兩個字串和一個數字 n。該函式匹配這兩個字串,即它檢查這兩個字串是否包含相同的字元。如果兩個字串都包含相同的字元,無論其順序如何,或者如果它們最多包含 n 個不同的字元,則該函式應返回 true,否則該函式應返回 false。

讓我們為該函式編寫程式碼 −

示例

const str1 = 'first string';
const str2 = 'second string';
const wildcardMatching = (first, second, num) => {
   let count = 0;
   for(let i = 0; i < first.length; i++){
      if(!second.includes(first[i])){
         count++;
      };
      if(count > num){
         return false;
      };
   };
   return true;
};
console.log(wildcardMatching(str1, str2, 2));
console.log(wildcardMatching(str1, str2, 1));
console.log(wildcardMatching(str1, str2, 0));

輸出

控制檯中的輸出將是 −

true
true
false

更新於: 2020 年 8 月 31 日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程,獲得認證

開始
廣告