美文网首页
3. Longest Substring Without Rep

3. Longest Substring Without Rep

作者: 闷油瓶小张 | 来源:发表于2016-12-13 20:16 被阅读17次

Given a string, find the length of the longest substring without repeating characters.
Examples:
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. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.


Solution

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    var a = s.split('');
    var length = a.length;
    var p1 = 0;
    var p2 = 0;
    var hash = [];
    var number = 0;
    while (p2 < length) {
        if (hash[a[p2]] !== undefined) {
            p1 = Math.max(hash[a[p2]] + 1, p1);
        }
        hash[a[p2]] = p2 ++;
        number = Math.max(p2 - p1, number);
    }
    return number;
};

相关文章

网友评论

      本文标题:3. Longest Substring Without Rep

      本文链接:https://www.haomeiwen.com/subject/hvpbmttx.html