LeetCode 无重复字符的最长子串

题目

给定一个字符串,请你找出其中不含有重复字符的最长子串的长度

思路

unordered__set 具备set互异性的特点,同时对插入的数据保留原顺序,即unordered。

本题的思想为“滑动窗口”,用unordered_set记录已扫描的字符,在插入前判断当前字符是否存在在已扫描的序列中。若存在,则删除最前的字符,直到与当前字符重复的字符被删除。

例如,efgabcda,当扫描到a时,要将efga都删除。

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() == 0)   return 0;
        int left = 0;
        int max_len = 0;
        unordered_set<char> myset;
        for(int i = 0; i < s.size(); i++){
            //当在已扫描过的序列中,找的到当前字符时,删除最前面的那个
            while(myset.find(s[i]) != myset.end()){
                myset.erase(s[left++]);
            }
            max_len = max(max_len, i - left + 1);
            //插入到已扫描的序列中
            myset.insert(s[i]);
        }
        return max_len;
    }
};
原文地址:https://www.cnblogs.com/woxiaosade/p/12376568.html