[Algorithm] Longest Substring Without Repeating Characters?

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

"wke"
"pwke"

 

Solution:

In the naive approaches, we repeatedly check a substring to see if it has duplicate character. But it is unnecessary. If a substring s_{ij}sij from index ii to j - 1j1 is already checked to have no duplicate characters. We only need to check if s[j]s[j] is already in the substring s_{ij}sij.

To check if a character is already in the substring, we can scan the substring, which leads to an O(n^2)O(n2) algorithm. But we can do better.

By using HashSet as a sliding window, checking if a character in the current can be done in O(1)O(1).

A sliding window is an abstract concept commonly used in array/string problems. A window is a range of elements in the array/string which usually defined by the start and end indices, i.e. [i, j)[i,j) (left-closed, right-open). A sliding window is a window "slides" its two boundaries to the certain direction. For example, if we slide [i, j)[i,j) to the right by 11 element, then it becomes [i+1, j+1)[i+1,j+1) (left-closed, right-open).

Back to our problem. We use HashSet to store the characters in current window [i, j)[i,j) (j = ij=i initially). Then we slide the index jj to the right. If it is not in the HashSet, we slide jj further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index ii. If we do this for all ii, we get our answer.

 

复制代码
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let begin = 0, max = 0;
    let hash = new Set();
    
    for (let end = 0; end < s.length; end++) {
        if (hash.has(s[end])) {
            while (s[begin] !== s[end]) {
                // delete chars until the dulpicate one
                hash.delete(s[begin++]);
            }
            // delete dulpicate one
            hash.delete(s[begin++]);
        }
        
        hash.add(s[end])
        max = Math.max(max, hash.size)

    }
    return max;
};
复制代码

 

posted @   Zhentiw  阅读(353)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-04-07 [Angular 2] Using Promise to Http
2016-04-07 [Angular 2] *ngFor with index
点击右上角即可分享
微信分享提示