1684838553 / arithmeticQuestions

程序员的算法趣题
2 stars 0 forks source link

字符串操作 #25

Open 1684838553 opened 1 year ago

1684838553 commented 1 year ago

indexOf(searchElement, fromIndex) // fromIndex 开始查找的位置。 sentence.replace(new RegExp(word,'g'), ' ') replace中使用变量

1684838553 commented 1 year ago

面试题 17.17. 多次搜索

/**
 * @param {string} big
 * @param {string[]} smalls
 * @return {number[][]}
 */
var multiSearch = function(big, smalls) {
    let result = []
    smalls.forEach(item => {
        const position = getPosition(big, item)
        result.push(position)
    })
    return result
};

const getPosition = (big, str) => {
   const ans = []
   if(!str || str.length > big.length) return ans
   let index = big.indexOf(str)
   while(index > -1){
       ans.push(index)
       index = big.indexOf(str, index + str.length)
   }
   return ans
}