I need to find the length of the longest substring in a string, I do it by this:
var lengthOfLongestSubstring = function(s) {
let arr = [];
let obj = {};
for(let i = 0; i<s.length; i++){
if(arr.indexOf(s[i])!==-1){
copy=arr.slice();
obj[i]=copy;
arr=[];
arr.push(s[i])
}
else{
arr.push(s[i]);
}
}
console.log(obj)
return Object.values(obj).reduce((acc, nextItem)=>{
if(acc&acc.length>=nextItem&&nextItem.length){
return acc.length;
}
else{
return nextItem.length
}
}, [])
};
console.log (lengthOfLongestSubstring ('abcabcbb'));
For test case "abcabcbb" it returns 1 instead of 3 and I don't understand why; btw what complexity (in terms of big O) would my code achieve?
the variant you have should work, just fix few typos in your code:
return Object.values(obj).reduce((acc, nextItem) => acc >= nextItem.length ? acc.length : nextItem.length , 0)