【问题标题】:What is the space complexity of this longest palindrome function?这个最长回文函数的空间复杂度是多少?
【发布时间】:2023-03-24 05:42:01
【问题描述】:
function longestPalindromicSubstring(str) {
    let longest = '';
    for ( let i = 0; i < str.length; i++) {
         let word1 = palindromeFinder(str, i, i );
         let word2 = palindromeFinder(str, i, i+1);
         longest = [ word1, word2, longest ].reduce( (long, word) => long.length > word.length ? long : word)
    }
    return longest;
}

function palindromeFinder(str, left, right) {
    while ( left >= 0 && right < str.length && str[left] === str[right] ) {
        left--;
        right++;
    }
    return str.slice(left + 1, right)
} 

我很确定时间复杂度是 O(n^2),因为主要的 for 循环乘以辅助函数中的循环。在for 循环中,我使用了reduce 函数,但它只对输入字符串中的每个元素执行2-3 次操作......我假设O(n^2) 是错误的吗?

我的主要问题是:这个函数O(1)的空间复杂度是多少?

我最多存储 3 个变量 longest, word1, word2,这样可以使其保持不变,对吗?

【问题讨论】:

    标签: javascript time-complexity big-o space-complexity


    【解决方案1】:

    什么导致空间复杂度?

    1. 变量
    2. 数据结构
    3. 函数调用
    4. 分配

    这些东西占用空间,当涉及到时间和空间复杂度时,会考虑最坏的情况并忽略恒定时间 (O(1))。

    但是,您的函数分配了变量、新的数据结构、函数调用,这使得空间复杂度为 O(n),此外,数组的每个项目都会消耗额外的空间。

    【讨论】:

      【解决方案2】:

      这个函数的空间复杂度是O(n),因为你存储了恒定数量的数据结构,每个都依赖于n:str、word1、word2、longest . O(1)其实就是常数,肯定不是这样的

      【讨论】:

        猜你喜欢
        • 2018-09-09
        • 2020-12-03
        • 2017-09-11
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 2021-07-03
        • 2015-11-29
        相关资源
        最近更新 更多