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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclass{ publicintlengthOfLongestSubstring(String s){ if(s == null || s.length() == 0){ return0; } Set<Character> set = new HashSet<Character>(); int max = 0, i = 0, j = 0; while(j < s.length()){ if(!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); max = Math.max(max, set.size()); } else { set.remove(s.charAt(i++)); } } return max; } }
近期评论