Without Repeating Characters: as a result, Integer value in HashMap would better keep record of the index where this character occur than freq. Two pointers should always increase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution { public int lengthOfLongestSubstring(String s) { HashMap<Character, Integer> map = new HashMap<>(); int i, j = 0, res = 0; for (i = 0; i < s.length(); ++i) { if (map.containsKey(s.charAt(i))) { j = Math.max(j, map.get(s.charAt(i)) + 1); } map.put(s.charAt(i), i); res = Math.max(res, i - j + 1); } return res; } }
HashSet or int[256] for mapping are both possible but I am too lazy to write them.