力扣刷题:3. 无重复字符的最长子串

题目要求

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

题目链接

提示

在这里插入图片描述

我的代码

class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        unordered_set<char> set;
        unsigned lenth = s.size();
        int left = 0, right = 0, maxLenth = 0;
        while (left < lenth)
        {
    
    
            while (right < lenth && set.count(s[right]) == 0)
            {
    
    
            set.insert(s[right++]);
            }

            maxLenth = std::max(maxLenth, right - left);
            set.erase(s[left++]);
        }
        return maxLenth;
    }

};

学到的东西

1、滑动窗口的运用:left和right的区间限定了分析子串。通过控制left,使得该子串不局限于“起点要从最左边开始”。通过依次移动right,使得最终能够分析完整个字符串。

2、无序容器set的运用:此题set保存了分析子串所具有的字符。并且通过set的count函数来判断新的字符是否已经存在于已经保存的分析子串中。

3、leetcode的c++环境:
using namespace std;
自动包含所需的容器头文件
目前看来什么都能用?

猜你喜欢

转载自blog.csdn.net/youyadefeng1/article/details/113402649