ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
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; }; ```