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.
Solution:
1 Public classSolution {2 Public intlengthoflongestsubstring (String s) {3 if(S.isempty ())return0;4Set<character> set =NewHashset<character>();5 intHead = 0, end = 1;6Set.add (S.charat (0));7 intMaxLen = 1;8 intCurlen = 1;9 while(end<s.length ()) {Ten CharCur =S.charat (end); One if(!set.contains (cur)) { A set.add (cur); -curlen++; -end++; the}Else { - while(S.charat (head)! =cur) { - Set.remove (S.charat (head)); -curlen--; +head++; - } +head++; Aend++; at } - if(Curlen>maxlen) maxlen=Curlen; - } - - - returnMaxLen; in } -}
Leetcode-longest Substring without repeating characters