--- tags: LeetCode,Top 100 Liked Questions --- # 3.Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/ ## 題目敘述 Given a string s, find the length of the longest substring without repeating characters. 找出**不重複**的**最長連續**子字串 Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. ## 解題想法 我們可以一個個char遍歷,當右邊的char出現在遍歷過的char中,去掉重複的char,將新的char加入遍歷過的char,重覆到字串結尾 //利用HashMap紀錄位置和出現過的char - 1.silde window silde window往字串右邊滑動,右邊char有3種情況: - 1.char出現過且在window中->window的left指向此char的前一格 - 2.char出現過不在window中(不影響window)->window直接往右 - 3.char沒出現過->window直接往右 ```c++=class Solution { public: int lengthOfLongestSubstring(string s) { int res=0,left=-1;//res:紀錄最長子字串長度 left:紀錄silde window 的左邊界 unordered_map<int, int> m; for(int i=0;i<s.length();i++){ if(m.count(s[i]) && m[s[i]]>left){ //m.count(s[i])-->有沒有出現過 //m[s[i]]>left -->char有沒有在window中 left=m[s[i]];//若char出現且在window->把left指向現在位置 } m[s[i]]=i; res=max(res,i-left); } return res; } }; ``` 時間複雜度 O(N)