使用 JavaScript 統計並返回出現在 str2 中的 str1 字數
問題
我們需要編寫一個 JavaScript 函式,它把兩個字串作為第一個和第二個引數接收,分別是 str1 和 str2。
我們的函式應該統計並返回出現在 str2 中的 str1 字元數,如果有重複出現,我們必須單獨統計。
例如,如果輸入函式的是
輸入
const str1 = 'Kk'; const str2 = 'klKKkKsl';
輸出
const output = 5;
樣例
以下是程式碼 −
const str1 = 'Kk';
const str2 = 'klKKkKsl';
var countAppearances = (str1 = '', str2 = '') => {
const map = {}
for(let c of str1) {
map[c] = true
}
let count = 0
for(let c of str2) {
if(map[c]) {
count+=1
}
}
return count
};
console.log(countAppearances(str1, str2));輸出
5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP