Problem

given height = Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

JavaScript Code

function lengthOfLongestSubstring(s) {
     
    var arr = s.split('');
    var pre = 0, len;
 
    var map = {};
 
    for (var i = 0; i < arr.length; i++) {
        if (map[arr[i]]==null) {
            map[arr[i]] =  i;
        } else {
            len = Object.keys(map).length;
            pre = Math.max(pre, len);
            i = map[arr[i]];
            map = {};
        }
    }
    len = Object.keys(map).length;
    return Math.max(pre, len);
}
console.log(lengthOfLongestSubstring('abcabcbb'));

0 comments:

Blogroll

Popular Posts