📌  相关文章
📜  使用Binary Search具有K个唯一字符的最长子字符串(1)

📅  最后修改于: 2023-12-03 15:22:18.064000             🧑  作者: Mango

使用Binary Search找到具有K个唯一字符的最长子字符串

在字符串中找到具有K个唯一字符的最长子字符串是一个常见问题。下面将介绍如何使用Binary Search来解决这个问题。

解决思路

首先,确定可以找到最长子字符串的最大长度。由于字符集有限,所以最长子字符串的长度最大为字符串的长度。因此,可以对长度进行Binary Search,直到找到具有K个唯一字符的最长子字符串。

对于每个长度 len,可以使用双指针的方法来检查是否存在具有K个唯一字符的子字符串。具体而言,首先统计字符串中长度为 len 的子字符串的出现次数。然后,使用两个指针 leftright 来遍历字符串,其中 left 是子字符串的左侧指针,right 是子字符串的右侧指针。对于每个指针,可以使用出现次数数组来检查子字符串是否具有K个唯一字符。如果子字符串具有K个唯一字符,则记录下来。在遍历完成字符串后,就可以找到具有K个唯一字符的最长子字符串。

代码实现

下面是使用Python编写的实现代码:

def k_unique_substring(s, k):
    def is_valid(subs_cnt, k):
        return sum(cnt >= 1 for cnt in subs_cnt) == k

    n = len(s)
    cnt = [0] * 26
    left = right = 0
    max_len = -1
    res = ""
    while right < n:
        cnt[ord(s[right]) - ord('a')] += 1
        while not is_valid(cnt, k):
            cnt[ord(s[left]) - ord('a')] -= 1
            left += 1
        if right - left + 1 > max_len:
            max_len = right - left + 1
            res = s[left:right+1]
        right += 1
    return res
参考文献
  • "Longest Substring with At Most K Distinct Characters" on LeetCode: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
  • "Python Sliding Window" on LeetCode: https://leetcode.com/explore/learn/card/sliding-window/239/conclusion/1393/