Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        Map<Character, Integer> map = new HashMap<>();

        int res = 0;
        // pos records the start index of the substring.  
        // set -1 to pos to include the 1st char of original string if there is no repeating characters found.
        int pos = -1;
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if (map.containsKey(c)) {
                // check which one is closer, current start index or the last index of current char.
                pos = Math.max(pos, map.get(c));
            }
            map.put(c, i);
            // pos is not counted in the length as it's the index of the repeating chars.
            res = Math.max(res, i - pos);
        }
        return res;
    }
}