LeetCode Notebook 2020-2021
  • 序
  • 目录
  • 线性表
    • 数组
      • Remove Duplicates from Sorted Array
      • Remove Duplicates from Sorted Array II
      • Exercises I
      • Search in Rotated Sorted Array
      • Search in Rotated Sorted Array II
      • Median of Two Sorted Arrays
      • Longest Consecutive Sequence
      • Exercises II
      • Two Sum
      • 3Sum
      • 3Sum Closest
      • 4Sum
      • Exercises III
      • Next Permutation
      • Permutation Sequence
      • Exercises IV
      • Valid Sudoku
      • Trapping Rain Water
      • Rotate Image
      • Plus One
      • Exercises V
      • Climbing Stairs
      • Set Matrix Zeroes
      • Gray Code
      • Gas Station
      • Exercises VI
      • Candy
      • Single Number
      • Single Number II
      • Exercises VII
    • 链表
      • Add Two Numbers
      • Reverse Linked List II
      • Partition List
      • Swap-nodes-in-pairs
  • 字符串
    • 字符串
      • Valid Palindrome
      • Implement strStr()
      • String to Integer(atoi)
      • Add Binary
      • Longest Palindromic Substring
      • Longest Common Subsequence
      • Regular Expression Matching
      • Rearrange Spaces Between Words
      • Longest Common Prefix
      • Wildcard Matching
      • subdomain visit count
  • 栈和队列
    • 栈
      • Min Stack
      • Valid Parentheses
    • 队列
  • 树
    • 二叉树的遍历
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Postorder Traversal
      • Search in a Binary Search Tree
    • 二叉树的构造
      • Untitled
    • 二叉查找树
      • Validate Binary Search Tree
    • 二叉树的递归
      • Untitled
  • 图
    • 图
  • 排序
    • 排序
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
      • Exercises I
      • Insertion Sort List
      • Sort List
      • Sort Color
      • First Missing Positive
      • Exercises II
  • 查找
    • 查找
      • Random Pick with Weight
      • Prefix and Suffix Search
      • Search Insert Position
      • Search a 2D Matrix
  • BFS
    • BFS
  • DFS
    • DFS
      • Split a String Into the Max Number of Unique Substrings
      • Palindrome Partitioning
      • Unique Path
      • Unique Path II
  • 动态规划
    • DP
      • Coin Change
      • Maximal Rectangle
      • Super Egg Drop
      • Exercises
      • Best Team With No Conflicts
  • 分治法
    • Divide And Conquer
  • 贪心法
    • Greedy
      • Jump Game
      • Jump Game II
      • Best time to buy and sell stock
      • Best time to buy and sell stock II
      • Container with most water
      • Exercises
  • 暴力枚举
    • Brute Force
      • Subsets
      • Subsets II
      • Permutation
      • Permutation II
      • Combinations
      • Letter Combinations of a Phone Number
  • others
    • 小岛题
    • 滑动窗口
      • Longest substring without repeating characters
      • Sliding Window Maximum
      • Max Consecutive One III
      • Count Number of Nice Subarrays
    • Roman number code
    • Untitled
由 GitBook 提供支持
在本页
  • Longest substring without repeating characters
  • 描述
  • 例子
  • 解法: Brute Force (Time Limit Exceeded)
  • 解法:slide window
  • 解法:slide window optimized
  • 解法 ASCII 表

这有帮助吗?

  1. others
  2. 滑动窗口

Longest substring without repeating characters

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

上一页滑动窗口下一页Sliding Window Maximum

最后更新于4年前

这有帮助吗?

Longest substring without repeating characters

描述

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

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        unordered_set<char> seen;
        int ans = 0,i=0,j=0;
        while(i<n&&j<n){
            if(!seen.count(s[j])){
                seen.insert(s[j++]);
                ans=max(ans,j-i);
            }else{
                seen.erase(s[i++]);
            }
        }
        return ans;
    }
};

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

解法:slide window optimized

class Solution {
public:
     int lengthOfLongestSubstring(string s) {
           int res = 0, left = 0, right = 0;
           unordered_map<char, int> map;
           while (right < s.size() && left + res < s.size()) {
               if (map.find(s[right]) != map.end()) {
                   left = max(left, map[s[right]] + 1);
               }
               map[s[right]] = right;
               res = max(res, right - left + 1);
   			right++;
           }

           return res;
       }
};

解法 ASCII 表

class Solution {
public:
     int lengthOfLongestSubstring(string s) {
         int n = s.length(), ans = 0;
         vector<int> index;
         index.assign(128,0);
        // current index of character
        // try to extend the range [i, j]
         for (int j = 0, i = 0; j < n; j++) {
            i = max(index[s[j]], i);
            ans = max(ans, j - i + 1);
            index[s[j]] = j + 1;
         }
        return ans;
    }
};
原题链接