アルゴリズム: 繰り返し文字を含まない最長の文字列 3. 繰り返し文字を含まない最長部分文字列

3. 繰り返し文字を含まない最長の部分文字列

文字列 s を指定して、文字を繰り返さない最長の
部分文字列の長さを見つけます。

例 1:

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

例 2:

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

例 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.

制約:

  • 0 <= s.length <= 5 * 104
  • s は、英語の文字、数字、記号、スペースで構成されます。

1. ダブルポインターマップは最初の文字 +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. カウンターカウンターの実装

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. カウンターの説明

Python では、Counter は、ハッシュ可能なオブジェクトの出現を数えるコレクション モジュールのクラスです。これは、リスト、タプル、文字列などのコレクション内の要素の出現をカウントする便利な方法を提供します。
Counter クラスは、コレクション内の要素をキーとして、対応する値をそれらの要素の出現数として整数値として表した辞書のようなオブジェクトを作成します。
以下は、Counter クラスとその使用法の基本的な説明です。

  • Counter クラスをインポートする:
    Counter を使用する前に、コレクション モジュールからそれをインポートする必要があります。
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_obj がリスト my_list から作成されます。リスト内の各要素の数をキーと値のペアとして Counter オブジェクトに保存します。

  • カウントへのアクセス:
    辞書から値にアクセスするのと同じように、キーによって特定の要素のカウントにアクセスできます。
count_of_3 = counter_obj[3]
print(count_of_3)  # 输出:3

  • 共通メソッド:
    Counter クラスには、最も多く出現した上位 n 個の要素とその数を返す most_common() など、多くの便利なメソッドが用意されています。
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) メソッドは、文字列内で最も頻繁に出現する上位 2 つの要素とその数を返します。
Counter クラスは、コレクション内の要素の出現数をカウントする必要がある場合、特に大規模なデータセットまたはテキスト処理タスクを扱う場合に便利です。

おすすめ

転載: blog.csdn.net/zgpeace/article/details/131907327