标签:
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.
Hash Table Two Pointers String
#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