Leetcode 3 Longest Substring Without Repeating Characters. (Longest substring of characters without repetition) (sliding window, double pointer)

table of Contents

Leetcode 3

Problem Description

Given a string, find the length of the longest substring without repeating characters.

example

Example 1:
Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

method

  A reserved character string is stored as the key and the position is stored as a value hashmap, and keep a pointer to define the maximum two sub-strings. The right to move the pointer to browse the string while updating hashmap. If the character is already in hashmap, the pointer will be left to the right end of the same characters found. Note that the two pointers can only move forward.

** Solution Java **
** 7ms, 79.25% **
** 41.9MB, 5.20% **
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) return s.length();
        Map<Character, Integer> map = new HashMap<>();
        int cur = 0, max = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (map.containsKey(s.charAt(i))) {
                cur = Math.max(cur, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i - cur + 1);
        }
        return max;
    }
}
** Solution Python3 **
** 56ms, beats 76.40% **
** 13MB, beats 99.49% **
class Solution:
    def lengthOfLongestSubstring(self, s) :
        cur = maxLength = 0
        usedChar = {}
        for index, char in enumerate(s) :
            if char in usedChar and cur <= usedChar[char]:
                cur = usedChar[char] + 1
            else:
                maxLength = max(maxLength, index - cur + 1)
            usedChar[char] = index
        return maxLength

Guess you like

Origin www.cnblogs.com/willwuss/p/12275316.html