共计 1178 个字符,预计需要花费 3 分钟才能阅读完成。
标题答案
var str = ‘abcabcbb’;
getLongStr(str);
// getLongStr(‘aa’);
function getLongStr(str) {
if(!str) {
return ‘ 字符串为空 ’;
}
if(str.length === 1) {
return 1;
}
var arr = str.split(”);
var obj = {};
var strArr = [];
var nStr = ”
var j = 0;
// 取出来所有不含重复字符的字符串
for(var i = 0, len = arr.length; i < len; i++) {
var val = arr[i];
if(obj[val]) {
i = j;
j++;
obj = {};
strArr.push(nStr);
nStr = ”;
} else {
obj[val] = true;
nStr += val;
}
}
// 取出来最长的字符串
var longIndex = strArr[0].length;
for (var i = 1, len = strArr.length; i < len; i++) {
var nLen = strArr[i].length;
var nVal = strArr[i];
if (nLen > longIndex) {
longIndex = nLen;
}
}
return longIndex;
}
备忘
问题:给定一个字符串,请你找出其中不含有重复字符的最长子串?答案如下:
// getLongStr(‘abcabcbb’);
// getLongStr(‘aa’);
function getLongStr(str) {
str += ”;
if(!str) {
return ‘ 字符串为空 ’
}
if(str.length === 1) {
return str;
}
var arr = str.split(”);
var obj = {};
var strArr = [];
var nStr = ”
var j = 0;
// 取出来所有不含重复字符的字符串
for(var i = 0, len = arr.length; i < len; i++) {
var val = arr[i];
if(obj[val]) {
i = j;
j++;
obj = {};
strArr.push(nStr);
nStr = ”;
} else {
obj[val] = true;
nStr += val;
}
}
// 取出来最长的字符串
var longIndex = strArr[0].length;
var longArr = [strArr[0]]
for (var i = 1, len = strArr.length; i < len; i++) {
var nLen = strArr[i].length;
var nVal = strArr[i];
if (nLen > longIndex) {
longIndex = nLen;
longArr = [nVal];
}
if (nLen === longIndex) {
longArr.push(nVal)
}
}
return […new Set(longArr)].join();
}