码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_3题——Longest Substring Without Repeating Characters(set,哈希表,两个指针)

时间:2015-05-09 20:23:00      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Longest Substring Without Repeating Characters

 Total Accepted: 62719 Total Submissions: 298285My Submissions

 

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.

 

Hide Tags
 Hash Table Two Pointers String
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
#include<string>
#include <map>
#include <set>
using namespace std;

int lengthOfLongestSubstring(string s) {
	
	if(s.size()==0)
		return 0;
	if(s.size()==1)
		return 1;
	string::iterator i1=s.begin();//设置指针i1
	string::iterator i2=s.begin()+1;//设置指针i2
	set<char> temp;
	temp.insert(*i1);
	int last_max=1;//最终值
	int max_num=1;//中间记录值

	/*每次在set型中储存当前的数据,当来了一个i2时,先考虑是否里面有,若是有的话就将i1指针
	直到这个数的后面一个数上,将temp中的之前那些数都给删掉,重新开始记录多少个数*/
	while(i2!=s.end())//直到i2到达末尾
	{
		if(temp.count(*i2)==0)
		{
			temp.insert(*i2);
			max_num=max_num+1;
			if(max_num>last_max)
				last_max=max_num;
			i2++;
		}
		else
		{
			int k=0;
			for(string::iterator j=i1;;j++)//将i1到*i2这个数在前面中的那个数之之间都给删掉
			{
				if((*j)==(*i2))
				{
					temp.erase(*i2);
					k++;
					break;
				}
				else
				{
					temp.erase(*j);
					k++;
				}
			}
			i1=i1+k;
			if(max_num>last_max)
				last_max=max_num;
			max_num=max_num-k;
		}

	}
	return last_max;
}

int main()
{
	string str="abcabcbb";
	cout<<lengthOfLongestSubstring(str)<<endl;
}

  

leetcode_3题——Longest Substring Without Repeating Characters(set,哈希表,两个指针)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4490922.html

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