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.
Public class solution {public static int lengthoflongestsubstring (string s) {int COUNT = 0; int start = 0; int max = 0; Map <character, integer> map = new hashmap <character, integer> (); For (INT I = 0; I <S. length (); I ++) {If (map. containskey (S. charat (I ))! = True) {count ++; map. put (S. charat (I), I);} else {If (max <count) max = count; If (start <map. get (S. charat (I) Start = map. get (S. charat (I); Count = I-start; map. put (S. charat (I), I) ;}} if (max <count) max = count; return Max ;}}
Train of Thought: O (n) solution, traverse strings, add one by one, use hashmap to check whether there are repeated characters, update the length and the starting coordinate of statistics.
The code below is more concise.
Public class solution {public static int lengthoflongestsubstring (string s) {int start = 0; int max = 0; Map <character, integer> map = new hashmap <character, integer> (); For (INT I = 0; I <S. length (); I ++) {If (map. containskey (S. charat (I) = true) {If (start <= map. get (S. charat (I) Start = map. get (S. charat (I) + 1; // Update start index} map. put (S. charat (I), I); If (max <(I-start + 1) max = I-start + 1; // update max} return Max ;}}