Longest substring without repeating characters

medium 原题链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/

Longest substring without repeating characters

原题链接arrow-up-right

描述

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

例子

Input: s = "abcabcbb"

Output: 3

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

解法: Brute Force (Time Limit Exceeded)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        int ans = 0;
        for(int i=0; i<n; i++){
            for(int j=i+1; j<=n; j++){
                if(allUnique(s,i,j)) ans=max(ans,j-i);
            }
        }
        return ans;
    }
    
    bool allUnique(string s,int start, int end){
        unordered_set<char> seen;
        for(int i=start; i<end; i++){
            char ch=s[i];
            if(seen.count(ch))return false;
            seen.insert(ch);
        }
        return true;
    }
};

分析:time:O(n^3),space:O(min(m,n))

解法:slide window

分析:time:O(2n)=O(n);space:O(min(m,n))。

解法:slide window optimized

解法 ASCII 表

最后更新于

这有帮助吗?