力扣——无重复字符的最长子串

在这里插入图片描述
在这里插入图片描述

1.使用unordered_set,思想是队列的,但是队列没有find函数,所以用无序set

#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <string> 
using namespace std;
int fun(string s);
int main()
{
	string s;
	getline(cin, s);
	cout << fun(s);
}
int fun(string s)
{
	if (s.size() == 0)
	{
		return 0;
	}
	int left = 0;
	int MAX = 0;
	unordered_set<char> a;
	for (int i = 0; i < s.size(); i++)
	{
		while (a.find(s[i]) != a.end())
		{
			a.erase(s[left]);
			left++;
		}
		MAX = max(MAX, i - left + 1);
		a.insert(s[i]);

	}
	return MAX;

}

2.今天学的双“指针”法

#include <iostream>
#include <algorithm>
#include <string> 
using namespace std;
int fun(string s);
int main()
{
	string s;
	getline(cin, s);
	cout << fun(s);
}
int fun(string s)
{
int i = 0,j,k,max = 0,len;
        for(j=i;j<s.size();j++){
            for(k=i;k<j;k++){
                if(s[k]==s[j]){
                    len = j-i;
                    if(len > max) max =len;
                    i = k+1;
                    break;
                }
            }
        }
        return j-i>max?j-i:max;
}

极简之道,建议不懂得朋友们画图试一试“abcdacb”这个字符串的流程,草稿本上试一次流程就明白了

3.另一种双指针

#include <iostream>
#include <algorithm>
#include <algorithm>
#include <string> 
using namespace std;
int fun(string s);
int main()
{
	string s;
	getline(cin, s);
	cout << fun(s);
}
int fun(string s)
{
	int start = 0, end = 0, maxlen = 0;
	char map[256] = { 0 };
	map[(int)(s[start])] = 1;

	while ((s[end]) != 0)
	{
		maxlen = maxlen > (end - start + 1) ? maxlen : (end - start + 1);
		++end;
		while (0 != map[(int)(s[end])])//将要加入的新元素与map内元素冲突
		{
			map[(int)(s [start])] = 0;
			++start;
		}
		map[(int)(s[end])] = 1;
	}

	return maxlen;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值