题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    int lengthOfLongestSubstring(string s) {
        // write code here
        // 滑动窗口,定义左右指针,没重复的字符就右指针右移扩大窗口,
        // 窗口内出现重复字符,左指针移动到重复字符的下一个位置上
        // 每一步都更新最长子字符串长度
        // 存储字符和最新的索引
        unordered_map<char, int> charIndexMap;
        int maxLength = 0; // 最长子字符串长度
        int left = 0;

        for (int right = 0; right < s.length(); ++right) {
            char currentChar = s[right];

            // 如果字符已经存在且其索引还在窗口范围内,移动左指针
            if (charIndexMap.find(currentChar) != charIndexMap.end()
                && charIndexMap[currentChar] >= left) {
                    left = charIndexMap[currentChar] + 1;
                }
            
            // 更新字符最新的索引
            charIndexMap[currentChar] = right;

            // 计算当前无重复字符子字符串长度
            maxLength = max(maxLength, right - left + 1);
        }

        return maxLength;
    }
};

全部评论

相关推荐

04-02 16:49
门头沟学院 Java
_bloodstream_:我也面了科大讯飞,主管面的时候听说急招人优先考虑能尽快实习的,我说忙毕设,后面就一直没消息了
点赞 评论 收藏
分享
ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务