Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 3. Longest Substring Without Repeating Characters

Rain Hu

3. Longest Substring Without Repeating Characters


一、題目

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

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

sliding window

三、解題

1. Sliding Window

int lengthOfLongestSubstring(string s) {
    int cnt[128] = {0};
    int left = 0, right = 0;
    int res = 0;
    while (right < s.length()) {
        char c = s[right++];
        while (cnt[c]) {        // 若 window 中已有該字元,則滑動左指標
            char d = s[left]++;
            cnt[d]--;           // 將 window 中,左指標的字元數減 1
        }
        res = max(res, right - left);   // 比較當前的長度
        cnt[c]++;   // 將 window 中,右指標的字元數加 1
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 4. Median of Two Sorted Arrays
Next
[LeetCode] 2. Add Two Numbers