# [3\. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) - 滑動視窗的大小不固定的例子。 - 搭配 HashMap 儲存滑動視窗的 Index。 - 初始值:`curLen`, `maxLen`, 左右滑動視窗的邊界 `i` 和 `j`。 - for loop 移動右邊界 `j`,如果發現重複的字元,更新左邊界 `i`。 - `curLen = j - i + 1`。 - 不斷取最大的 `maxLen` 值。 :::spoiler Solution ```cpp= class Solution { public: int lengthOfLongestSubstring(string s) { int curLen = 0, maxLen = 0; unordered_map<char, int> m; int left = 0; for (int right = 0; right < s.size(); ++right) { if (m.count(s[right])) { // 如果發現重複字元,則更新左邊界 left = max(left, m[s[right]]); } curLen = right - left + 1; maxLen = max(maxLen, curLen); // 更新右邊界的位置為 right + 1 m[s[right]] = right + 1; } return maxLen; } }; ``` - 時間複雜度:$O(N)$ - 空間複雜度:$O(\min(M, N))$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up