【问题标题】:std: bad_alloc runtime error in javascript code标准:JavaScript 代码中的 bad_alloc 运行时错误
【发布时间】:2022-08-06 11:21:31
【问题描述】:

我正在解决 leetcode 中的一个问题。问题是找到最长子串的长度。我解决了这个问题,代码在本地机器上运行良好,当我在 leetcode 游乐场上运行代码时。但是当我提交代码时,它会显示 std:bad_alloc 的运行时错误。

这是我的代码

const lengthOfLongestSubstring = (s) => {
  const allSubstring = [];
  let subIndex = 0;
  let count = 0;
  while (count < s.length) {
      allSubstring.push(s.substring(count, subIndex + 1));
      subIndex += 1;
      if (subIndex === s.length) {
          count += 1;
          subIndex = count;
      }
  }

  const valid = [];

  allSubstring.forEach((a) => {
      let validStr = \'\';
      a.split(\'\').forEach((s, i) => {
          if (!validStr.includes(s)) {
              validStr += s;
          }
      });
      if (a.includes(validStr)) 
valid.push(validStr);
  });

  let longestSubString = \'\';
  valid.forEach((i) => {
      if (longestSubString.length < i.length) {
          longestSubString = i;
      }
  });

  return longestSubString.length;
}

我是 leetcode 的新手。我想知道这段代码有什么问题?

    标签: javascript substring bad-alloc


    【解决方案1】:

    如果超出 Leetcode 为问题分配的内存空间,就会出现此错误。您的解决方案存储每一个可能的 2^n 子字符串,每个子字符串最多有 n 个字符:O(n * 2^n),这是相当高的。您可能想提出一个更有效的解决方案来通过测试用例。

    出于学习目的,这里有一个线性空间和时间的解决方案:https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/731639/JavaScript-Clean-Heavily-Commented-Solution

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多