Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  27] [ 5]  / answers: 1 / hits: 20930  / 7 Years ago, fri, march 24, 2017, 12:00:00

The problems asks given a string, find the longest non-repeating sub-string without repeating characters. I am a little stumped why returning my code is not working for the string dvdf for example. Here is my code :



function lengthOfLongestSubstring(check) {
var letters = check.split();
var max = 0;
var result = [];
for (var i = 0; i < letters.length; i++) {
var start = i
if (result.indexOf(letters[i]) === -1) {
result.push(letters[i])
} else {
i = i - 1
result = []
}
if (max === 0 || max < result.length) {
max = result.length
}
}
return max
}

More From » javascript

 Answers
51

This implementation gives the correct result for dvdf.



It adds characters to current_string while there is no duplicate. When you find a duplicate cut current_string to the point of the duplicate. max is the max length current_string had at any time. This logic seems correct to me so I think it's correct.



function lengthOfLongestSubstring(string) {
var max = 0, current_string = , i, char, pos;

for (i = 0; i < string.length; i += 1) {
char = string.charAt(i);
pos = current_string.indexOf(char);
if (pos !== -1) {
// cut dv to v when you see another d
current_string = current_string.substr(pos + 1);
}
current_string += char;
max = Math.max(max, current_string.length);
}
return max;
}

lengthOfLongestSubstring(dvdf); // 3


The value of current_string in each round is , d, dv, vd, vdf.


[#58399] Thursday, March 23, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
natalyah

Total Points: 371
Total Questions: 90
Total Answers: 105

Location: The Bahamas
Member since Wed, Apr 12, 2023
1 Year ago
;