Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "ABCABCBB" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.
Hide TagsHash Table Pointers String This question has the front foundation actually is very simple, http://www.cnblogs.com/Azhu/p/4127606.html thought similar, uses the double index to indicate the target's head and tail, the left index points to the first which can go, the right index points to the first that does not take, then the initialization is 0, The length is right-left, and the two are equal to indicate that the substring is empty. Attention:
- The substrings are different from the subsequence, the substrings need to be contiguous, the sub-sequences are only required in order, and do not require continuous.
- It is important to indicate that a good substring (window) is clear that the index is pointing inside the window.
- Because of the need to tag characters, so intuitively think of is hash_map or unordered_map, but based on ASCII as long as a 128-bit bool array, discuss they declared as 256, but with 128 passed.
- Array subscripts If you use characters directly as if implicit conversions fail, you need to add a cast.
Algorithm implementation:
- Initializes the window index lft=rgt=0, initializing the tag array at the same time, indicating whether that one character is inside the window.
- Right index traversal string
-
- If you encounter a character rgt+1 that is not inside the window, change flag to calculate the length of the oldest string update.
- If inside the window, lft+1, change flag, re-judge the character of the RGT position.
I wrote the code:
1#include <iostream>2#include <string>3 using namespacestd;4 5 classSolution {6 Public:7 intLengthoflongestsubstring (strings) {8 intn =s.length ();9 if(n<2)returnN;Ten intLFT =0, RGT =0, MaxLen =0; One BOOLsign[ -] = {false}; A while(rgt<N) { - //cout<<lft<< "" <<rgt<< "" <<maxlen<<endl; - if(Sign[(int) s[rgt]]==false){ thesign[(int) s[rgt]]=true; -rgt++; - if(maxlen<rgt-lft) MaxLen = RGT-LfT; - Continue; + } -sign[(int) S[lft]] =false; +lft++; A } at returnMaxLen; - } - }; - - intMain () - { in strings="242522f23r23rt432twrfs122"; - solution Sol; toCout<<sol.lengthoflongestsubstring (s) <<Endl; + return 0; -}
View Code
[Leetcode] Longest Substring without repeating characters longest non-repeating substring