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; }; ```