# Longest Substring Without Repeating Characters

xiaoxiao2021-02-28  13

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size() == 1) return 1; if(s.size() == 0) return 0; const char *ss = s.c_str(); set<char> SetS; set<char>::iterator it; int MaxS = 1; int CurrentS = 1; int FirstL = 0; int LastL = 1; SetS.insert(ss[FirstL]); for(int i=0; i< s.length();i++) { it = SetS.find(ss[LastL]); if(it !=SetS.end()) { if(CurrentS > MaxS) MaxS = CurrentS; for(int j = FirstL;;) { if(ss[LastL] == ss[j]) { FirstL = j+1; break; } else { j++; CurrentS--; SetS.erase(ss[j-1]); } } } else { SetS.insert(ss[LastL]); CurrentS++; } if(LastL == s.size() -1 ) break; LastL++; } if(CurrentS > MaxS) return CurrentS; return MaxS; } };注意事项：各种边界条件，坑爹的SET还有就是C++忘得差不多了，一道题写了3个小时，难受