算法分析(不同字符的子字符串最大长度)


#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int lengthOfLongestSubstring(string s)
{
	if (!s.size()) return 0;

	const char* cp = s.c_str();// 将string 转换成一个  const char * 格式
	/*std::map<char, int> mapStr; map is slower than vector 71% -> 99% */
	vector<int> mapStr(256, 0);// 一维256长度的向量,初始化全部为0
	int start = 1;
	int end = 1;
	int max = 0;

	while (true)
	{
		char cha = *cp;   //cp 是第一个字符的地址,*cp 是第一个字符

		if (cha == '\0')
		{
			break;  //读取到字符串结尾时退出
		}

		/*if get same char, wo need calculate the length, and store the best */
		if (mapStr[cha] != 0)
		{
			/*wo do not need care the position if it samller than the start position
			becase [ a, b, d, e, f, d, a] , the a -> a list is broken by d, and  start position is 4(d + 1)*/
			if (mapStr[cha] >= start)
			{
				int length = end - start;
				if (max < length)
				{
					max = length;
				}

				start = mapStr[cha] + 1;
			}
		}

		mapStr[cha] = end;

		cp = cp + 1;
		end += 1;
	}

	int c = end - start;

	if (c > max)
	{
		max = c;
	}

	return max;
}

int main()
{
    cout << "Hello World!\n";
	string  str;
	cin >> str;
	int a = lengthOfLongestSubstring(str);
	cout << "这个字符串最大不重复的子字符个数为" << a << endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值