程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了获取 JS 函数的时间和空间复杂度大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决获取 JS 函数的时间和空间复杂度?

开发过程中遇到获取 JS 函数的时间和空间复杂度的问题如何解决?下面主要结合日常开发的经验,给出你关于获取 JS 函数的时间和空间复杂度的解决方法建议,希望对你解决获取 JS 函数的时间和空间复杂度有所启发或帮助;

这里'我有一个删除连续重复字符的问题的解决方案。但我需要知道这个解决方案的时间和空间复杂度。

功能如下:

@H_301_8@function removeAdjacentDuplicates(str){ for (let i = 0; i< str.length -1; i++){ if(str[i] === str[i+1] && i+2==str.length){ return str.substr(0,i); } else if(i+2==str.length ||str=="" || str.length==0){ return str; } else if (str[i] === str[i+1]){ return removeAdjacentDuplicates(str.substr(0,i)+str.substr(i+2,(str.length)-(i+2))); } } }; //removeAdjacentDuplicates('abbc') returns 'ac'

我猜两者都应该是 O(n),因为对于每个输入,函数都需要遍历整个函数。也将感谢改进功能的建议。

解决方法

我想一个简单的 reduce 就足够了,not too complex 在这里。

如何确定复杂性是explained nicely here。此外,还有很多关于该主题的文章(例如 here 或 here)。

See also

console.log(`original: abba and,sommmme of thaat ook??`,` `);
console.log(`removeAdjacentDuplicates: ${
  removeAdjacentDuplicates('abba and,sommmme of thaat ook??')}`);
console.log(`removeDuplicateCharacterPairs: ${
  removeDuplicateCharacterPairs('abba and,sommmme of thaat ook??')}`);
console.log(`RemoveConcurrentCharacters: ${
    RemoveConcurrentCharacters([...'abba and,sommmme of thaat ook??'])}`);
console.log(`RemoveConcurrentCharactersReducer: ${
  RemoveConcurrentCharactersReducer([...'abba and,sommmme of thaat ook??'])}`);

// this removes one of duplicate character pairs
function removeAdjacentDuplicates(str) {
  return str.split('')
    .reduce((acc,val) =>
      val === acc.slice(-1) ? acc : acc + val,'');
}

// this removes actual duplicate pairs,// but the result may contain new duplicates
function removeDuplicateCharacterPairs(str,result = []) {
  str = str.split("");
  const first = str.shift();
  str.length && first !== str[0] && result.push(first) || str.shift();
  return str.length ?
    removeDuplicateCharacterPairs(str.join(""),result) :
    result.join("");
}

// this removes duplicate pairs. When the result
// contains new duplicate pairs removes them too
// so the result will not contain any duplicate
// character pair
function RemoveConcurrentCharacters(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i += 1) {
    const len = result.length - 1;

    i < 1 && result.push(arr[i]);

    if (i > 0) {
      arr[i] !== result[len] &&
        result.push(arr[i]) ||
        result.splice(len,1);
    }
  }
  return result.join("");
};

// making a round trip: RemoveConcurrentCharacters can be
// condensed using a reducer method.
function RemoveConcurrentCharactersReducer(arr) {
  return arr.reduce((acc,val) =>
      !acc.length ? [val] : val === acc[acc.length-1] ? 
        acc.slice(0,-1) : [...acc,val],[])
    .join("");
};

大佬总结

以上是大佬教程为你收集整理的获取 JS 函数的时间和空间复杂度全部内容,希望文章能够帮你解决获取 JS 函数的时间和空间复杂度所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。