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.
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function(s) { let max = 0 let str = '' for(let i = 0; i < s.length; i++) { if (str.includes(s[i])) { str = str.substring(str.indexOf(s[i]) + 1) + s[i] } else { str += s[i] } max = Math.max(max, str.length) } return max };
思路
這題是要找到最長的不重複連續字串數,因此最終不是要得到該字串,只要紀錄數字即可。
我的作法是做一個暫存連續字串的變數。
假設題目是 “pwawkew”,比對到 “pwa” 時,下一個字是 “w”,出現了重複的字串。這邊把字串從第一個 “w” 切掉,從 “aw” 繼續比對。
每一個 loop 再檢測目前最長連續的字串數。