//给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
function lengthOfLongestSubstring(s) {
// 创建一个 Map 用于存储字符和它们的索引
const charIndexMap = new Map();
let maxLength = 0; // 用于记录最长子串的长度
let startIndex = 0; // 用于记录当前子串的起始索引
// 遍历字符串中的每个字符
for (let endIndex = 0; endIndex < s.length; endIndex++) {
const char = s[endIndex];
// 如果字符已经在 Map 中,并且其索引大于等于当前子串的起始索引
if (charIndexMap.has(char) && charIndexMap.get(char) >= startIndex) {
// 更新当前子串的起始索引为重复字符的下一个位置
startIndex = charIndexMap.get(char) + 1;
}
// 将字符及其索引存入 Map 中
charIndexMap.set(char, endIndex);
// 计算当前子串的长度,并更新最大长度
const currentLength = endIndex - startIndex + 1;
maxLength = Math.max(maxLength, currentLength);
}
return maxLength;
}
// 示例用法
const s1 = "abcabcbb";
console.log(lengthOfLongestSubstring(s1)); // 输出: 3
const s2 = "bbbbb";
console.log(lengthOfLongestSubstring(s2)); // 输出: 1
const s3 = "pwwkew";
console.log(lengthOfLongestSubstring(s3)); // 输出: 3
这段代码定义了一个JavaScript函数,用于在给定字符串中找到最长的无重复字符子串的长度。它使用Map数据结构来跟踪字符及其出现的位置,确保子串内没有重复字符。

2537

被折叠的 条评论
为什么被折叠?



