💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
link: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ > Given a string, find the length of the longest substring without repeating characters. Examples: ``` Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", 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. ``` # JavaScript ```js /** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function(s) { if (s === "") { return 0; } let subStr = []; let maxStr = []; s.split("").forEach((c, i) => { const pos = subStr.indexOf(c); // if character already exists if (pos !== -1) { // start tracking from just after old occurance of character subStr = subStr.slice(pos + 1, i); } // add new character subStr.push(c); // check if current is new longest if (subStr.length > maxStr.length) { maxStr = subStr.join(""); } }); return maxStr.length; }; ```