示例代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_set<int> mySet;
        //这里的start表示set中第一个元素在数组中的位置
        int len=s.length(),res=0,start=0;
        for(int i=0;i<len;i++){
            //如果能在set里面找到当前的值,就不断地从set头部开始移除元素,直到没有与当前重复的元素为止
            while(mySet.count(s[i])){
                //不断地移除下一个元素
                mySet.erase(s[start++]);
            }
            mySet.insert(s[i]);
            res=max(res,i-start+1);
        }
        return res;
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

效果展示

LeetCode---3. 无重复字符的最长子串(用set存储滑动窗口里面的元素,方便进行查找)_算法