给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    示例 1:

    1. 输入: "abcabcbb"
    2. 输出: 3
    3. 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3

    示例 2:

    1. 输入: "bbbbb"
    2. 输出: 1
    3. 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1

    示例 3:

    1. 输入: "pwwkew"
    2. 输出: 3
    3. 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3
    4. 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

    https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

    我的解:**

    1. class Solution {
    2. public int lengthOfLongestSubstring(String s) {
    3. if (s.length() == 0) return 0;
    4. int start = 0;
    5. int end = 1;
    6. int last = -1;
    7. int result = 0;
    8. Map<Character, Integer> map = new HashMap<>();
    9. map.put(s.charAt(start), 0);
    10. while (end < s.length()) {
    11. if (map.containsKey(s.charAt(end)) && map.get(s.charAt(end)) > last) {
    12. result = Math.max(end - start,result);
    13. last = map.get(s.charAt(end));
    14. start = last + 1;
    15. }
    16. map.put(s.charAt(end), end);
    17. end++;
    18. }
    19. result = Math.max(end - start,result);
    20. return result;
    21. }
    22. }

    image.png