【贪心算法】Longest Substring Without Repeating Characters

题目:leetcode

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

int lengthOfLongestSubstring(string s)
{
	if (s.size() <= 1)
		return s.size();
	bool pos[256];
	for (auto &i : pos)
	{
		i = false;
	}
	int res = 1, curlen = 1,begin=0;
	pos[s[0]] = true;
	for (int i = 1; i < s.size(); i++)
	{
		if (pos[s[i]] == false)
		{
			curlen++;
			pos[s[i]] = true;
		}
		else
		{
			res = max(res, curlen);
		//	char c = s[i];
		int j;
			for (j = begin;; j++)
			{
				if (s[j] == s[i])
				{
					j++;
					break;
				}
				pos[s[j]] = false;
			}
			begin = j;
			curlen = i - j + 1;
		}
	}
	res = max(res, curlen);
	return res;
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。