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

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. // 不包含重复字符的
  4. if (s == null || s.length() == 0) return 0;
  5. char[] chars = s.toCharArray();
  6. Map<Character,Integer> windows = new HashMap<>();
  7. int left = 0, right = 0, maxLen = 0, len = s.length();
  8. while (right < len) {
  9. char add = chars[right++];
  10. // 放入map中
  11. windows.put(add, windows.getOrDefault(add, 0) + 1);
  12. while (windows.get(add) > 1) {
  13. char remove = chars[left++];
  14. // update
  15. windows.put(remove, windows.get(remove) - 1);
  16. }
  17. // get maxLen
  18. maxLen = Math.max(maxLen, right - left);
  19. }
  20. return maxLen;
  21. }
  22. }