美文网首页
2020-07-07 3. Longest Substring

2020-07-07 3. Longest Substring

作者: 苦庭 | 来源:发表于2020-07-07 06:11 被阅读0次

https://leetcode.com/problems/longest-substring-without-repeating-characters

My answer / AC

/**
 * @param {string} s
 * @return {number}
 */


var lengthOfLongestSubstring = function(s) {
    if(s=="") return 0;
    if(s.length==1) return 1;
    
    let left = 0, right = 0, ans=0;
    let map = new Set();
    while(right<s.length && left<s.length) {
        
        if(!map.has(s[right])) {
            map.add(s[right]);
            right++;
            ans = Math.max(ans, right-left);

        } else {
            map.delete(s[left]);
            left++;
        }
    }
    console.log(map)
    return ans;
};

左指针用来表示当前处理字符串的头,右指针用来代表尾。
详见https://leetcode.wang/leetCode-3-Longest-Substring-Without-Repeating-Characters.html的解法1

Best answer

Recap

相关文章

网友评论

      本文标题:2020-07-07 3. Longest Substring

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