企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
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; }; ```