标签:
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.
第一次完全没有找参考做出来的题,开心。
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int n=s.size(); 5 if(n<2) return n; 6 map<char,int> strmap; 7 int begin=0; 8 int end=0; 9 int res=0; 10 for(int i=0;i<n;i++) 11 { 12 if(strmap.find(s[i])==strmap.end()) 13 { 14 strmap.insert(pair<char,int>(s[i],i)); 15 end=i; 16 } 17 else 18 { 19 if((end-begin+1)>res) res=end-begin+1; 20 if(begin<=strmap[s[i]]) begin=strmap[s[i]]+1; 21 end=i; 22 strmap[s[i]]=i; 23 } 24 } 25 if((end-begin+1)>res) res=end-begin+1; 26 return res; 27 } 28 };
Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/zl1991/p/4714077.html