Algorithm: The longest string without repeating characters 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

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

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

1. The double-pointer map records the position of the first letter +1

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)  # 获取字符串s的长度
        res = 0  # 初始化最长子串的长度为0
        mp = {
    
    }  # 创建一个字典mp用于存储字符和其最后出现的位置的映射
        l = 0  # 初始化左指针l为0,表示滑动窗口的左边界

        for r in range(n):  # 遍历字符串s,r为滑动窗口的右边界
            if s[r] in mp:  # 如果字符s[r]已经在字典mp中存在,说明它在滑动窗口中出现过
                l = max(l, mp[s[r]])  # 将左指针l更新为s[r]的最后出现位置的下一个位置,确保滑动窗口不包含重复字符

            res = max(res, r - l + 1)  # 更新最长子串的长度为当前滑动窗口的长度(r - l + 1)和之前的最大值之间的较大值
            mp[s[r]] = r + 1  # 将字符s[r]和其当前位置r+1添加到字典mp中,表示字符s[r]出现在位置r+1

        return res  # 返回最长子串的长度

2. Counter counter implementation

from collections import Counter

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        counter = Counter()  # Create a Counter to count character occurrences
        left = right = 0  # Initialize two pointers for the sliding window approach
        res = 0  # Initialize the variable to store the result (length of the longest substring)
        
        while right < len(s):  # Iterate over the characters in the input string
            r = s[right]  # Get the character at the 'right' pointer
            
            counter[r] += 1  # Increment the count of the character in the Counter
            
            while counter[r] > 1:  # If the count of the character is greater than 1 (duplicate found)
                l = s[left]  # Get the character at the 'left' pointer
                counter[l] -= 1  # Decrement the count of the character in the Counter
                left += 1  # Move the 'left' pointer to the right to remove the duplicate character
            
            res = max(res, right - left + 1)  # Update the result with the length of the current substring
            right += 1  # Move the 'right' pointer to the right to expand the window
            
        return res  # Return the length of the longest substring without repeating characters

3. Explain Counter

In Python, Counter is a class in the collections module that counts occurrences of hashable objects. It provides a convenient way to count the occurrences of an element in a collection such as a list, tuple, or string.
The Counter class creates a dictionary-like object with the elements in the collection as keys and the corresponding values ​​as the number of occurrences of those elements, expressed as an integer value.
Following is a basic explanation of the Counter class and its usage:

  • Import the Counter class:
    Before using Counter, you need to import it from the collections module:
from collections import Counter
  • Creating Counter Objects:
    You can create Counter objects by passing an iterable object such as a list, tuple, or string as an argument to the Counter constructor. For example:
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter_obj = Counter(my_list)
print(counter_obj)
# 输出:Counter({4: 4, 3: 3, 2: 2, 1: 1})

In this example, the Counter object counter_obj is created from the list my_list. It stores the count of each element in the list as a key-value pair in a Counter object.

  • Accessing the count:
    You can access the count of a specific element by key, just like accessing the value from a dictionary:
count_of_3 = counter_obj[3]
print(count_of_3)  # 输出:3

  • Common methods:
    The Counter class provides many useful methods, such as most_common(), which returns the top n elements with the most occurrences and their counts:
my_string = "hello"
counter_string = Counter(my_string)
most_common_elements = counter_string.most_common(2)
print(most_common_elements)
# 输出:[('l', 2), ('h', 1)]

In this example, the most_common(2) method returns the top two most frequently occurring elements in the string and their counts.
The Counter class is useful when you need to count the number of occurrences of an element in a collection, especially when dealing with large datasets or text processing tasks.

Guess you like

Origin blog.csdn.net/zgpeace/article/details/131907327