• Find the longest substring that does not contain repeated characters and calculate the length of the substring.
  • Example:
  1. "Abcabcbb" prints 3 because the oldest string without repeating characters is "ABC"
  2. "BBBBB" prints 1 because the oldest string without repetition is "B"
  3. "Pwwkew" prints 3 because the oldest string without repetition is "wKE"
  • Ideas:
  1. A Map is used to record the contents of strings. Because a Map cannot contain duplicate keys and a key cannot point to multiple values, characters are recorded as keys and indexes in strings are recorded as values, and values are updated each time.
  2. Record the result with a value and update the result every time it gets larger.
  3. Double pointer: an index that always points to the first character of a non-repeating string, and another pointer to update the pointed character.
  4. If the existing map contains the key, the index of the key is updated, that is, I, and the value of the original I is compared with the value of the existing key, whichever is larger.
  5. When adding a key-value pair to a map, the character-character index is added each time, and j++ is continuously traversed to update the key-value pair.
  6. Basically, a pointer goes all the way back, iterating, entering key-value pairs. The other pointer, which is sort of taking the value of the key, changing that value, changing I over and over again every time there’s a repeat element, returns j-i+1;
  • Code:
class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        int len = s.length();
        for (int i = 0, j=0; j < len; j++) {
            char ch = s.charAt(j);
            if (map.containsKey(ch)) {
                i = Math.max(i, map.get(ch));
            }
            res = Math.max(res, j-i+1);
            map.put(s.charAt(j),j+1);
        }
        returnres; }}Copy the code