【LeetCode 0003】【滑动窗口】无重复字符的最长子串

  1. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

复制代码
**Input:** s = "abcabcbb"
**Output:** 3
**Explanation:** The answer is "abc", with the length of 3.

Example 2:

复制代码
**Input:** s = "bbbbb"
**Output:** 1
**Explanation:** The answer is "b", with the length of 1.

Example 3:

复制代码
**Input:** s = "pwwkew"
**Output:** 3
**Explanation:** The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.
JavaScript Solution
javascript 复制代码
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let ans = 0
    if('' === s){
        return ans
    }   
    let [left,right] = [0,-1]
    // matain the mapping from character to isPresent Flag 
    let flags = {}
    while(left < s.length){
        // mark all different elements as 1s
        if(( right+1 ) < s.length && !flags[s[right+1]] ){
            flags[s[ right+1 ]] = 1
            right++
            ans = Math.max(ans,right-left+1)
        }else{
            // sliding leftmost 1s to 0s
            flags[s[left]] = 0
            left++
        }
     }
    return ans
};
相关推荐
PineappleCoder4 分钟前
大小写 + 标点全搞定!JS 如何精准统计单词频率?
前端·javascript·算法
zzx_blog13 分钟前
简单易懂的leetcode 100题-第三篇 移动0,颜色分类,数组中的第K个最大元素
leetcode·面试
tanyongxi661 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
qq_513970441 小时前
力扣 hot100 Day76
算法·leetcode·职场和发展
Moshow郑锴1 小时前
机器学习相关算法:回溯算法 贪心算法 回归算法(线性回归) 算法超参数 多项式时间 朴素贝叶斯分类算法
算法·机器学习·回归
liulilittle2 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路
剪一朵云爱着2 小时前
PAT 1065 A+B and C (64bit)
算法·pat考试
喜欢吃燃面2 小时前
C++算法竞赛:位运算
开发语言·c++·学习·算法
项目申报小狂人3 小时前
算法应用上新!自适应更新策略差分进化算法求解球形多飞行器路径规划问题,附完整MATLAB代码
开发语言·算法·matlab