STD:JavaScript代码中的BAD_ALLOC运行时错误
我正在解决Leetcode中的问题。问题是找到最长的子字符串的长度。我解决了该问题,并且当我在Leetcode Playground上运行代码时,代码正在完美运行。但是,当我提交代码时,它显示了具有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的新手。我想知道此代码中有什么问题?
I was solving a problem in leetcode. The problem was find the length of longest substring. I solved the problem and the code is running perfectly on local machine and when I run the code on leetcode playground. But when I submit the code it shows runtime error with std:bad_alloc.
here is my code
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;
}
I'm new at leetcode. I want to know what is wrong in this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您超过了LeetCode的分配内存空间,则会发生此错误。您的解决方案存储了可能的2^n子字符串中的每一个,每个子字节最多具有n个字符:O(n * 2^n),这很高。您想提出一个更有效的解决方案来通过测试用例。
出于学习目的,这是O(n)空间和时间的一个很好的解释解决方案: https://leetcode.com/problems/problems/longest-substring-without-without-repeating-characters/discuss/discuss/731639/731639/javascript-clean-heavily-heavily-heavily-comment-commented-solution < /a>。
This error occurs if you exceed Leetcode's allocated memory space for a submission. Your solution stores every one of the possible 2^n substrings, each of which has at most n characters: O(n * 2^n), which is quite high. You would want to come up with a more efficient solution to pass the test cases.
For learning purposes, here is a well-explained solution in O(n) space and time: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/731639/JavaScript-Clean-Heavily-Commented-Solution.