地址:http://ysm.missed.com.cn/game/maxstr.html 实现了三种方法
方法一
采用循环的方式,找出每个位置对应的最大字符串长度
function lengthOfLongestSubstring(s) {
var data = s.split('');
var tempmax = 1;
if(!data.length){return 0;}
for(var i=0;i<data.length;i++){
var str_arr = new Array();
str_arr.push(data[i]);
for(var j=(i+1);j<data.length;j++){
if(data[j]==data[i]){
var temp = j-i;
if(tempmax<temp){
tempmax = temp;
}
break;
}else{
if(str_arr.indexOf(data[j])==-1){
temp2 = j-i+1;
str_arr.push(data[j]);
if(tempmax<temp2){
tempmax = temp2;
}
}else{
break;
}
}
}
}
console.log(tempmax);
return tempmax;
};
方法二
非常精妙的方法
function lengthOfLongestSubstring2(s){
let stack = [], m = s.split(''), ticker = 0, maxCount = 0, i = 0
for(i; i < m.length; i++) {
let cur = m[i], q = stack.indexOf(cur)
if (q == -1) {
stack.push(cur)
ticker = stack.length
if (ticker > maxCount) {
maxCount = ticker
}
} else {
stack.splice(0, q + 1)
stack.push(cur)
ticker = stack.length
}
}
console.log(maxCount);
return maxCount
}
方法三
和方法二类似
function lengthOfLongestSubstring3(s) {
if(s===""){return 0};
var arr = s.split("");
var newarr = [ arr[0] ];
var newstr = arr[0];
var length =1; //字符串的长度
var index = 0; //重复下标
var substr = ""; //截取之后的字符串
for (var i = 0; i< arr.length-1; i++){
newstr = newarr.join("");
index = newstr.indexOf(arr[i+1]);
//下一位与之前的字符串是否有某个字节相同
if(index > -1){
length = Math.max(newstr.length,length);
newstr = newstr + arr[i+1];
substr = newstr.substring(index+1);
newarr = substr.split("");
}else{
newarr.push(arr[i+1]);
}
}
return (Math.max(length,newarr.length));
};