# 3.Longest Substring Without Repeating Characters <span class='tag' data-diff='medium'></span> {%hackmd RN5D4nggQRO8wzNqxuvlNw %} ## 題目 Given a string, find the length of the longest substring without repeating characters. **Example 1:** ``` Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. ``` **Example 2:** ``` Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. ``` **Example 3:** ``` Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. ``` ## 思路 本來一開始想用dynamic programming解,但發現他要求的是substring而非subsequence,殺雞焉用牛刀,所以改用loop來解。首先初始化一個空的臨時字串,和max變數用來記錄目前的不重複字元字串與最大長度。接者loop過每一個字元,將臨時字串從與當前字元重複的地方切開後,把當前字元加入到臨時字串中,並更新最大substring的長度,一輪之後即可得出解答。 ```javascript let temp = "", max = 0; for(let c of s){ max = Math.max(max, temp.length); temp = temp.slice(temp.indexOf(c) + 1); temp += c; } max = Math.max(max, temp.length); return max; ``` 這個方法在runtime與memory使用量上都可以贏過80%的人,潮爽der~~