0
点赞
收藏
分享

微信扫一扫

算法: 没有重复字符的最长字符串3. Longest Substring Without Repeating Characters

禾木瞎写 2023-07-25 阅读 48

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. 双指针map记录第一个字母的位置+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计数器实现

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. 解释 Counter

在Python中,Counter是collections模块中的一个类,用于计数可哈希对象的出现次数。它提供了一种方便的方式来计数集合(如列表、元组或字符串)中元素的出现次数。
Counter类创建了一个类似字典的对象,其中集合中的元素作为键,对应的值为这些元素的出现次数,计数以整数值表示。
以下是对Counter类及其用法的基本解释:

  • 导入Counter类:
    在使用Counter之前,需要从collections模块中导入它:
from collections import Counter
  • 创建Counter对象:
    您可以通过将可迭代对象(例如列表、元组或字符串)作为参数传递给Counter构造函数来创建Counter对象。例如:
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})

在这个例子中,Counter对象counter_obj由列表my_list创建。它将列表中每个元素的计数作为键-值对的形式存储在Counter对象中。

  • 访问计数:
    您可以通过键来访问特定元素的计数,就像从字典中访问值一样:
count_of_3 = counter_obj[3]
print(count_of_3)  # 输出:3

  • 常用方法:
    Counter类提供了许多有用的方法,例如most_common(),它返回出现次数最多的前n个元素及其计数:
my_string = "hello"
counter_string = Counter(my_string)
most_common_elements = counter_string.most_common(2)
print(most_common_elements)
# 输出:[('l', 2), ('h', 1)]

在这个例子中,most_common(2)方法返回字符串中出现次数最多的前两个元素及其计数。
Counter类在需要计算集合中元素出现次数的情况下非常有用,尤其是在处理大型数据集或文本处理任务时。

举报

相关推荐

0 条评论