Knowledge Reserve--Basic Algorithms-Sliding Window

1. Sliding window

1.1 Question 3 - The longest substring without repeated characters

Given a string  s , please find  the length of the longest substring  that does not contain repeated characters .

Example 1:

Input: s = "abcabcbb"
 Output: 3 
 Explanation: Because the longest substring without repeated characters is "abc", its length is 3.

Experience: Use the hash table to traverse a little bit, but because the hash table takes up memory, I traverse it in two loops, so the speed is slow and it takes up a lot of memory. 

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s)==0:
            return 0
        max_ = 1
        for i in range(len(s)):
            hash_table = {}
            max_temp = 0
            for j in range(i,len(s)):
                if s[j] not in hash_table:
                    hash_table[s[j]] = 1
                    max_temp += 1
                    if max_ < max_temp:
                        max_ = max_temp
                else:
                    break
        return max_

After reading the analysis, my overall idea is similar, but he used a sliding window, the amount of calculation is much less, and he did not understand the meaning of left at the beginning. left is used to delete elements from the left of the window until there is no more elements in the hash table. to the same elements. Also, don’t use {} when using set(). You need to use add and remove for set.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s)==0:
            return 0
        max_len = 0
        hash_table = set()
        cur_len = 0
        left = 0
        for j in range(len(s)):
            cur_len += 1
            while s[j] in hash_table:
                hash_table.remove(s[left])
                left += 1
                cur_len -= 1
            if max_len < cur_len:
                max_len = cur_len
            hash_table.add(s[j])
        return max_len

1.2 Question 438 - Find all character anagrams in the string

Given two strings  s sum  p, find  all  substrings of allophones s  in  and return the starting index of these substrings. The order of answer output is not taken into account.p 

Allophones  refer to strings formed by the rearrangement of the same letters (including identical strings).

Example 1:

Input: s = "cbaebabacd", p = "abc"
 Output: [0,6]
 Explanation:
The substring with starting index equal to 0 is "cba", which is an anagram of "abc".
The substring with starting index equal to 6 is "bac", which is an anagram of "abc".

Experience: The idea is very simple, I figured it out early, but I thought about the logic that the sliding window is equal to the given string for a long time, and finally decided to use a dictionary to record, and the repeated characters will be added to the value of the character in the dictionary One, delete or subtract one when sliding. Dictionary deletion operation uses del.

The reference answer uses an array to store the number of each letter.

class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        if len(s) < len(p):
            return []
        elif s == p:
            return [0]
        target_dict = {}
        n = len(p)
        for i in range(n):
            if p[i] not in target_dict:
                target_dict[p[i]] = 1
            else:
                target_dict[p[i]] = target_dict[p[i]] + 1
        result = []
        result_dict = {}
        for i in range(n-1):
            if s[i] not in result_dict:
                result_dict[s[i]] = 1
            else:
                result_dict[s[i]] = result_dict[s[i]] + 1
        for i in range(len(s)-n+1):
            if s[i+n-1] not in result_dict:
                result_dict[s[i+n-1]] = 1
            else:
                result_dict[s[i+n-1]] = result_dict[s[i+n-1]] + 1
            if result_dict == target_dict:
                result.append(i)
            if result_dict[s[i]] == 1:
                del result_dict[s[i]]
            else:
                result_dict[s[i]] = result_dict[s[i]] - 1
        
        return result

Guess you like

Origin blog.csdn.net/Orange_sparkle/article/details/132671650