码迷,mamicode.com
首页 > 编程语言 > 详细

【贪心算法】Longest Substring Without Repeating Characters

时间:2015-03-29 18:08:07      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:c++   程序员   面试   贪心算法   

题目: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;
}



【贪心算法】Longest Substring Without Repeating Characters

标签:c++   程序员   面试   贪心算法   

原文地址:http://blog.csdn.net/bupt8846/article/details/44728181

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!