📌  相关文章
📜  计算具有恰好 k 个不同字符的子字符串的数量

📅  最后修改于: 2022-05-13 01:57:06.492000             🧑  作者: Mango

计算具有恰好 k 个不同字符的子字符串的数量

给定字符串小写字母,计算所有可能具有恰好 k 个不同字符的子串(不一定不同)。
例子:

Input: abc, k = 2
Output: 2
Possible substrings are {"ab", "bc"}

Input: aba, k = 2
Output: 3
Possible substrings are {"ab", "ba", "aba"}

Input: aa, k = 1
Output: 3
Possible substrings are {"a", "a", "aa"}

方法1(蛮力)

如果字符串的长度为 n,则可能有 n*(n+1)/2 个可能的子字符串。一种简单的方法是生成所有子字符串并检查每个子字符串是否恰好有 k 个唯一字符。如果我们应用这种蛮力,将需要 O(n*n) 来生成所有子字符串,并且需要 O(n) 来检查每个子字符串。因此总的来说它会变成 O(n*n*n)。

方法二

该问题可以在 O(n*n) 中解决。想法是在生成子字符串并使用该哈希表检查唯一字符的数量时维护一个哈希表。
下面的实现假设输入字符串只包含从“a”到“z”的字符。
执行

C++
// C++ program to count number of substrings with
// exactly k distinct characters in a given string
#include
using namespace std;
 
// Function to count number of substrings
// with exactly k unique characters
int countkDist(string str, int k)
{
    int n = str.length();
 
    // Initialize result
    int res = 0;
 
    // To store count of characters from 'a' to 'z'
    int cnt[26];
 
    // Consider all substrings beginning with
    // str[i]
    for (int i = 0; i < n; i++)
    {
        int dist_count = 0;
 
        // Initializing array with 0
        memset(cnt, 0, sizeof(cnt));
 
        // Consider all substrings between str[i..j]
        for (int j=i; j k) break;
        }
    }
 
    return res;
}
 
// Driver Program
int main()
{
    string str = "abcbaa";
    int k = 3;
    cout << "Total substrings with exactly "
         << k <<" distinct characters :"
         << countkDist(str, k) << endl;
    return 0;
}


Java
// Java program to CountKSubStr number of substrings
// with exactly distinct characters in a given string
import java.util.Arrays;
 
public class CountKSubStr
{
    // Function to count number of substrings
    // with exactly k unique characters
    int countkDist(String str, int k)
    {
        // Initialize result
        int res = 0;
 
        int n = str.length();
 
        // To store count of characters from 'a' to 'z'
        int cnt[] = new int[26];
 
        // Consider all substrings beginning with
        // str[i]
        for (int i = 0; i < n; i++)
        {
            int dist_count = 0;
 
            // Initializing count array with 0
            Arrays.fill(cnt, 0);
 
            // Consider all substrings between str[i..j]
            for (int j=i; j


Python 3
# Python3 program to count number of
# substrings with exactly k distinct
# characters in a given string
 
# Function to count number of substrings
# with exactly k unique characters
def countkDist(str1, k):
    n = len(str1)
     
    # Initialize result
    res = 0
 
    # To store count of characters from
    # 'a' to 'z'
    cnt = [0] * 27
 
    # Consider all substrings beginning
    # with str[i]
    for i in range(0, n):
        dist_count = 0
 
        # Initializing array with 0
        cnt = [0] * 27
 
        # Consider all substrings between str[i..j]
        for j in range(i, n):
             
            # If this is a new character for this
            # substring, increment dist_count.
            if(cnt[ord(str1[j]) - 97] == 0):
                dist_count += 1
 
            # Increment count of current character
            cnt[ord(str1[j]) - 97] += 1
 
            # If distinct character count becomes k,
            # then increment result.
            if(dist_count == k):
                res += 1
            if(dist_count > k):
                break
 
    return res    
 
# Driver Code
if __name__ == "__main__":
    str1 = "abcbaa"
    k = 3
    print("Total substrings with exactly", k,
           "distinct characters : ", end = "")
    print(countkDist(str1, k))
 
# This code is contributed by
# Sairahul Jella


C#
// C# program to CountKSubStr number of substrings
// with exactly distinct characters in a given string
 
  
using System;
public class CountKSubStr
{
    // Function to count number of substrings
    // with exactly k unique characters
    int countkDist(string str, int k)
    {
        // Initialize result
        int res = 0;
  
        int n = str.Length;
  
        // To store count of characters from 'a' to 'z'
        int[] cnt = new int[26];
  
        // Consider all substrings beginning with
        // str[i]
        for (int i = 0; i < n; i++)
        {
            int dist_count = 0;
  
            // Initializing count array with 0
            Array.Clear(cnt, 0,cnt.Length);
  
            // Consider all substrings between str[i..j]
            for (int j=i; j


PHP


Javascript


输出:

Total substrings with exactly 3 distinct characters : 8

时间复杂度: O(n*n)

空间复杂度:O(1)
解释:只使用了 26 大小的数组,可以认为是常量空间。