###### tags: `leetcode`, `javascript` # 【LeetCode】Javascript - #3. Longest Substring Without Repeating Characters --- ### 題目: Given a string s, find the length of the longest substring without repeating characters. --- ### 大概翻譯: 給定一個字串s,求最長子字串的長度,不包含重複字元。 --- 例如: ```javascript= Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. 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. ``` --- ```javascript= var lengthOfLongestSubstring = function(s) { // 追蹤每個字的索引值 const seen = new Map(); // 追蹤當前子字串的索引值 let start = 0; // 追蹤最大子字串長度 let maxLen = 0; for(let i = 0; i < s.length; i++) { // 如果看到當前字元,則將開始移動到(1+此字元的最後一個索引) if(seen.has(s[i])) { start = Math.max(seen.get(s[i]) + 1, start) } seen.set(s[i], i); // 當前子字串長度和最大長度的最大值 maxLen = Math.max(i - start + 1, maxLen); } return maxLen; }; ``` ![](https://i.imgur.com/lTpYWc1.png) --- *新手工程師的筆記,純粹記錄學了些啥東西 如果有前輩高人讀了我的文,文中有任何錯誤再麻煩指教指教*