ADV <B> analyze LeetCode #3 — Longest Substring Without Repeating Characters 3/99

Perfect! Let’s analyze LeetCode #3 — Longest Substring Without Repeating Characters using the Algorithm / Data Structure / Variable pattern.


🌳 Longest Substring Without Repeating Characters — Three-Level Analysis

Problem Statement

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


🧠 1. Algorithm Level — Logic and Rules

Goal: Find the maximum length substring with all unique characters.

Steps (Sliding Window Approach)

  1. Use two pointers left and right to define a window of characters.
  2. Expand right to include new characters.
  3. If a character is repeated within the window, move left forward until the window is unique.
  4. Track the maximum window size encountered.

Key Idea

  • Sliding window ensures O(n) time complexity.
  • Greedy: expand as long as substring is unique; shrink when repetition occurs.

C++ Code

int lengthOfLongestSubstring(string s) {
    unordered_map<char, int> mp; // char -> last index
    int left = 0, maxLen = 0;
    for (int right = 0; right < s.size(); right++) {
        if (mp.count(s[right]) && mp[s[right]] >= left) {
            left = mp[s[right]] + 1; // move left past repeated char
        }
        mp[s[right]] = right; // update last index
        maxLen = max(maxLen, right - left + 1);
    }
    return maxLen;
}

📦 2. Data Structure Level — What Actually Changes

Data StructurePurposeHow it Changes
Hash Map mpTracks last index of each characterUpdated as we encounter each character: mp[s[right]] = right
String sInput dataRead-only, used to check characters
WindowConceptual substring [left, right]Moves dynamically as left and right pointers change

Example Trace (for s = "abcabcbb"):

Step 0: left=0, right=0, mp={}, maxLen=0
Step 1: s[0]='a', mp={} → mp={'a':0}, maxLen=1
Step 2: s[1]='b', mp={'a':0} → mp={'a':0,'b':1}, maxLen=2
Step 3: s[2]='c', mp={'a':0,'b':1} → mp={'a':0,'b':1,'c':2}, maxLen=3
Step 4: s[3]='a', repeated → move left=mp['a']+1=1, update mp['a']=3, maxLen=3
...

🧮 3. Variable Level — How Memory & Values Are Manipulated

VariableRoleExample / Update
leftStart of windowMoves forward when repetition detected (left = mp[s[right]] + 1)
rightEnd of windowIterates over string (for right=0..s.size()-1)
maxLenMax lengthUpdated each step: maxLen = max(maxLen, right-left+1)
mpStores last occurrencemp[s[right]] = right
  • Variables are temporary storage and indices used to manipulate the window and hash map.
  • Hash map updates are a CRUD operation: insert new character or update last index.

🧩 Summary Table

LevelFocusC++ ConceptCRUD / OperationExample
AlgorithmSliding window logicLoop, pointer updateRead & update substringExpand right, shrink left on repeat
Data StructureTrack character positionsunordered_map<char,int>Insert / Update / Findmp[s[right]] = right
VariableTemporary computationleft, right, maxLenCompute window size & indicesleft = mp[s[right]]+1, maxLen = max(maxLen, right-left+1)

Key Insight

  • Algorithm defines what to do (slide window, handle repeats).
  • Data structures track state (map of last seen indices).
  • Variables store temporary values and control window movement (mechanics of the algorithm).

Perfect! Let’s create a step-by-step table showing how the sliding window, hash map, and variables evolve in LeetCode #3 — Longest Substring Without Repeating Characters.

We’ll use this example:

s = "abcabcbb"

🌳 Longest Substring Without Repeating Characters — Step-by-Step

Steprights[right]leftHash Map mp (char → last index)maxLenAction / Notes
00‘a’0{} → {‘a’:0}1No repetition, expand window
11‘b’0{‘a’:0} → {‘a’:0,‘b’:1}2No repetition, expand window
22‘c’0{‘a’:0,‘b’:1} → {‘a’:0,‘b’:1,‘c’:2}3No repetition, expand window
33‘a’0 → 1{‘a’:0,‘b’:1,‘c’:2} → {‘a’:3,‘b’:1,‘c’:2}3‘a’ repeated → move left past last ‘a’
44‘b’1 → 2{‘a’:3,‘b’:1,‘c’:2} → {‘a’:3,‘b’:4,‘c’:2}3‘b’ repeated → move left past last ‘b’
55‘c’2 → 3{‘a’:3,‘b’:4,‘c’:2} → {‘a’:3,‘b’:4,‘c’:5}3‘c’ repeated → move left past last ‘c’
66‘b’4 → 5{‘a’:3,‘b’:4,‘c’:5} → {‘a’:3,‘b’:6,‘c’:5}3‘b’ repeated → move left past last ‘b’
77‘b’6 → 7{‘a’:3,‘b’:6,‘c’:5} → {‘a’:3,‘b’:7,‘c’:5}3‘b’ repeated → move left past last ‘b’

🔹 Explanation

  1. right iterates over the string.
  2. left adjusts whenever a repeated character is detected in the current window.
  3. mp keeps track of the last index of each character.
  4. maxLen is updated if the current window (right-left+1) is larger than the previous max.

🔹 Algorithm / Data Structure / Variable Perspective

LevelFocusExample from Table
AlgorithmSliding window logic, repeat handlingExpand right, shrink left when a repeat is found
Data StructureState tracking of charactersunordered_map<char,int> updated with last seen indices
VariableTemporary computation / indicesleft, right, maxLen

Key Insight:

  • Algorithm: defines the sliding window and repeat handling.
  • Data Structure: hash map tracks characters dynamically (CRUD operations: insert/update/find).
  • Variables: store pointers and temporary values to compute window size.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值