【34】无重复字符的最长子串(LeetCode 3)

无重复字符的最长子串

问题描述

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

解题思想

unordered_set的使用:

unordered_set<int> c1; //定义
c1.empty();//判断是否为空
c1.size(); //获取元素个数 size()
c1.max_size(); //获取最大存储量 max_size()
c1.find(key);//调用 unordered_set 的 find() 会返回一个迭代器。这个迭代器指向和参数哈希值匹配的元素,如果没有匹配的元素,会返回这个容器的结束迭代器end()。
c1.insert(key);//插入元素
c1.erase(key);//根据key值删除元素
c1.clear();//清空
c1.count(key)//返回容器中元素出现的次数

滑动窗口的思想:假设不重复字符的子串以第i个字符开头,此时第i个字符处于窗口的第一个元素,当新加入的字符不满足要求时,窗口就往右移动一个,将第i个字符挤出去。

class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        int n=s.size();
        if(n == 0) return 0;
        unordered_set<char> lookup;
        int res = 0,start = 0;
        for(int i = 0; i < n; i++){
    
    
            while (lookup.find(s[i]) != lookup.end()){
    
     //若在容器中找到了相应的元素则执行
                lookup.erase(s[start]);
                start++;
            }
            res = max(res,i-start+1);
            lookup.insert(s[i]);
    }
        return res;
        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43424037/article/details/113730595