I was asked this question in a recent interview. I need to find the longest substring
without repeating characters.
Given "abcabcbb
", the answer is "abc
", which the length is 3.
Given "bbbbb
", the answer is "b
", with the length of 1.
Given "pwwkew
", the answer is "wke
", with the length of 3
This is what I came up with, I think it works correctly, but the interviewer was not impressed and said that my solution may not work for all cases.
var str = "pwwkew";
var longSubstring = function(str) {
var obj = {}; //map object
var count = 0;
var c = []; //count array to keep the count so far
for (var i = 0; i < str.length; ++i) {
//check if the letter is already in the map
if (str[i] in obj && obj[str[i]] !== i) {
c.push(count); //we encountered repeat character, so save the count
obj = {};
obj[str[i]] = i;
count = 1;
continue;
} else {
obj[str[i]] = i;
++count;
}
}
return Math.max.apply(null, c);
}
console.log(longSubstring(str)); //prints 3
Can anyone tell me what's the problem with my solution? I think it is one of the best :) and also solves in O(n)
time.