剑指 Offer 48. 最长不含重复字符的子字符串

这一题我的初始想法就就是直接hashSet,不整花里胡哨的,遇到重复的直接另起炉灶即可
更好的做法就是滑动窗口,看一下图就可以了,很简单

  1. public int lengthOfLongestSubstring(String s) {
  2. Map<Character, Integer> dic = new HashMap<>();
  3. int i = -1, res = 0;
  4. for(int j = 0; j < s.length(); j++) {
  5. if(dic.containsKey(s.charAt(j)))
  6. i = Math.max(i, dic.get(s.charAt(j))); // 更新左指针 i
  7. dic.put(s.charAt(j), j); // 哈希表记录
  8. res = Math.max(res, j - i); // 更新结果
  9. }
  10. return res;
  11. }