package offer100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class LengthOfLongestSubstring {
    int maxLen = 0;

    public int lengthOfLongestSubstring(String s) {
        char[] arr = s.toCharArray();
        Map<Character, List<Integer>> idxMap = new HashMap<>();
        List<Integer> idxList;
        for (int i = 0; i < arr.length; i++) {
            idxList = idxMap.get(arr[i]);
            if (null == idxList) {
                idxList = new ArrayList<Integer>();
                idxMap.put(arr[i], idxList);
            }
            idxList.add(i);
        }

        for (int i = 0; i < arr.length; i++) {
            findMaxLen(arr, 0, idxMap);
        }
        return maxLen;
    }

    private void findMaxLen(char[] arr, int be, Map<Character, List<Integer>> idxMap) {
        int end = arr.length;
        for (int i = be; i < end || end - be < maxLen; i++) {
            end = Math.min(end, findNextIdx(be, idxMap.get(arr[i])));
        }

        if (end - be > maxLen) {
            maxLen = end - be;
        }

    }

    private int findNextIdx(int cur, List<Integer> idxList) {
        // todo binary search
        for(int i = 0; i < idxList.size(); i++) {
            if (idxList.get(i) == cur) {
                if (i + 1 < idxList.size()) {
                    return idxList.get(i + 1);
                } else {
                    return Integer.MAX_VALUE;
                }
            }
        }
        return Integer.MAX_VALUE;
    }
}
package offer100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class LengthOfLongestSubstring {
      public int lengthOfLongestSubstring(String s) {
        // 最大不重复 -> 滑动窗口
          
        // 哈希集合，记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格，移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }
}

Update LengthOfLongestSubstring.java