13.无重复字符的最长子串每一加注释了更好得理解

这段代码定义了一个JavaScript函数,用于在给定字符串中找到最长的无重复字符子串的长度。它使用Map数据结构来跟踪字符及其出现的位置,确保子串内没有重复字符。

 //给定一个字符串 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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值