3. 无重复字符的最长子串 ---- 滑动窗口、无序集合存放比较、erase()删除

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

 

示例 1:

输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
  请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
 

提示:

0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() == 0) return 0; // 长度为0时, 返回0
        unordered_set<char> lookup; // 建立无序集合
        int maxStr = 0; // 设立最长字串
        int left = 0; // 左指针
        for(int i = 0; i < s.size(); i++){ // 遍历字符串
            while (lookup.find(s[i]) != lookup.end()){ // 如果集合里的值等于(末尾)新添加的值 或 lookup.count(s[i) 
                lookup.erase(s[left]); // 删除集合最左边的字符,直到整个集合没有相等值
                left ++; //指针++
            }
            maxStr = max(maxStr,i-left+1); // 判断是否更新最大值
            lookup.insert(s[i]); // 将字符添加进集合
    }
        return maxStr;
        
    }
};

erase()删除指定元素或范围内元素:

  Iterators specifying a range within the vector] to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.

 

lookup.find(s[i]) != lookup.end() 等价于 lookup.count(s[i]) C++11

posted @ 2022-11-17 14:04  slowlydance2me  阅读(18)  评论(0编辑  收藏  举报