当前位置: 首页 > Web前端 > JavaScript

LeetCode解法|3.无重复字符的最长子串Javascript

时间:2023-03-27 13:15:29 JavaScript

/***@param{string}str*@returnsnumber*思路:1.start和range组合成一个窗口,窗口中的子串是目前最长的不重复字符串*2.range每递增一次cycle*3.由于slice是左闭右开,所以range的初始值为1,获取当前元素时,range应该是-1*4,一个变量result存放的是当前的最终结果,一个变量resultTmp存储了当前的匹配结果。当当前匹配的resultTmp长度大于当前最终结果result的长度时,resultTmp覆盖当前最终结果result*5。当当前元素已经存在于最长子串resultTmp中时,将start的值改为下标+1*与resultTmp中的当前元素匹配(+1是为了新的开始不包含当前重复的字符)*(将start改为匹配的下标+1而不是range的值,因为下标+1之间的字符和范围不重复)*/functionlengthOfLongestSubstring(str){letstart=0;让范围=1;让结果=“”;让resultTmp="";while(range<=str.length){constindex=range-1;constfindIndex=resultTmp.indexOf(str[index]);如果(findIndex>-1){开始=findIndex+开始+1;}resultTmp=str.slice(start,range++);如果(resultTmp.length>result.length){result=resultTmp;}}console.log(result,result.length);返回结果.lengthh;}lengthOfLongestSubstring("abcabcbb");lengthOfLongestSubstring("bbbbb");lengthOfLongestSubstring("pwwkew");lengthOfLongestSubstring("");