Leetcode刷题笔记题解(C++):LCR 016.无重复字符的最长子串

Leetcode刷题笔记题解(C++):LCR 016.无重复字符的最长子串_第1张图片

思路:

利用滑动窗口的思想,用起始位置startindex和curlength来记录这个滑动窗口的大小,并且得出最长距离;利用哈希表来判断在滑动窗口中是否存在重复字符,代码如下所示:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //如果为空字符串,则返回0
        if(s.length() == 0) return 0;
        int maxlength = 0;//定义最长的字符串的长度
        int curlenth =0;//定义当前的不重复的字符串长度
        int startindex = 0;//滑动窗口的起始位置
        unordered_maphashtable;
        for(int i = 0;i maxlength) maxlength = curlenth;
                //更新滑动窗口的位置
                startindex = max(hashtable[s[i]],startindex);
                //当前的长度就为两个重复字符之间的长度
                //比如abcabcd   i=3 startindex=0 curlength=3
                curlenth = i - startindex;
                //更新重复字符最新出现的位置
                hashtable[s[i]] = i;
            }
        }
        //最后比较一下最后这个最长的字符串长度和上一个最大字符串的长度
        if(curlenth > maxlength) maxlength = curlenth;
        return maxlength;
    }
};

你可能感兴趣的:(Leetcode算法题解,leetcode,笔记,c++)