无重复字符的最长子串

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

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

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    	//双指针(i和j),一个一直向前,直到遇到一样的,另一个向前,不合理,pass
        set<char> temp;
        int max = 1, count = 0;
        if(s == "") return 0;
    
        for(auto i : s)
        {
            count = temp.size();
            temp.insert(i);

            if(max < temp.size())
                max = temp.size();
            if(count == temp.size()){
                temp.clear();
                for(auto i : temp)
                {
                    cout << i << " ";
                }
                temp.insert(i);
            }
            cout << endl << endl;
        }
        for(auto i : temp)
        {
            cout << i << endl;
        }
        return max;
    }
};
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //滑动窗口(暴力)O(n) = n^2
        set<char> temp;
        int max = 1, count = 0;
        int i = 0, j = 0;
        if(s == "") return 0;
    
        for(j = 0; j < s.size(); j++)
        {
            for(i = j; i < s.size(); i++)
            {
                count = temp.size();
                temp.insert(s[i]);

                if(max < temp.size())
                    max = temp.size();
                if(count == temp.size()){
                    temp.clear();
                    for(auto m : temp)
                    {
                        cout << m << " ";
                    }
                    break;
                }
                cout << endl << endl;
            }

        }
        for(auto m : temp)
        {
            cout << m << endl;
        }
        return max;
    }
};

思路:
这道题主要用到思路是:滑动窗口

什么是滑动窗口?

其实就是一个队列,比如例题中的 abcabcbb,进入这个队列(窗口)为 abc 满足题目要求,当再进入 a,队列变成了 abca,这时候不满足要求。所以,我们要移动这个队列!

如何移动?

我们只要把队列的左边的元素移出就行了,直到满足题目要求!

一直维持这样的队列,找出队列出现最长的长度时候,求出解!

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    	//滑动窗口O(n) = n
        if(s.size() == 0) return 0;
        unordered_set<char> lookup;
        int maxStr = 0;
        int left = 0;
        for(int i = 0; i < s.size(); i++){
        	//这里有set的用法,找s[i]在lookup里面是否存在。
            while (lookup.find(s[i]) != lookup.end()){
                //cout << lookup.find(s[i]) << "   " << lookup.end() << endl;
                lookup.erase(s[left]);
                left ++;
            }
            maxStr = max(maxStr,i-left+1);
            lookup.insert(s[i]);
        }
        return maxStr;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值