// 给定的字符串
const str = 'abac'
function outputMaxSubStrLen(str) {
let result = 0; // 最终要返回的结果的初始值
let norepeatStr = ''; // 用于存放无重复子串
let len = str.length; // 字符串的长度
// 遍历整个字符串
for (let i = 0; i < len; i++) {
// charAt()获取的是字符串索引对应的具体字符
// 当前遍历的字符串
let specStr = str.charAt(i);
// indexOf()查找的是某个字符第一次出现并返回这个索引值,若没有这个字符,返回-1
let index = norepeatStr.indexOf(specStr);
// 如果在存放无重复子串中没有当前字符串
if (index === -1) {
// 将遍历得到的字符(未重复)拼接在norepeatStr后面
norepeatStr = norepeatStr + specStr;
// 如果结果的长度小于存放无重复子串的长度,返回无重复子串的长度,否则返回
result = result < norepeatStr.length ? norepeatStr.length : result;
// 第一圈
// norepeatStr = "" + "a" =》"a"
// result = 0 < 1 ? 1 : 0 =》 1
// 第二圈
// norepeatStr = "a" + "b" =》 "ab"
// result = 1 < 2 ? 2 : 1 =》 2
// 第四圈
// norepeatStr = "ba" + "c" =》 "bac"
// result = 2 < 3 ? 3 : 2 =》 3
} else {
// 若遇到重复的字符,那么将已出现在norepeatStr里的字符删除,并将新的(重复的)添加到末尾
norepeatStr = norepeatStr.substr(index + 1) + specStr;
// 第三圈
// norepeatStr = "ab".substr(0 + 1) + "a" =》 "ba"
}
}
// 遍历完成后,得到无重复子串的长度
return result;
}
console.log(outputMaxSubStrLen(str))
前端面试题-给定一个字符串,找出其中无重复字符的最长子字符串长度
最新推荐文章于 2024-02-11 21:48:20 发布