📌  相关文章
📜  包含 K 个的二进制字符串的子串计数

📅  最后修改于: 2021-10-27 08:08:59             🧑  作者: Mango

给定一个长度为 N 的二进制字符串和一个整数 K,我们需要找出这个字符串中存在多少个正好包含 K 个的子串。

例子:

Input : s = “10010”
        K = 1
Output : 9
The 9 substrings containing one 1 are,
“1”, “10”, “100”, “001”, “01”, “1”, 
“10”, “0010” and “010”

在这个问题中,我们需要找到恰好包含 K 个的子串的计数,或者换句话说,这些子串中的数字总和为 K。我们首先创建一个前缀和数组并遍历它并在总和值大于或等于时停止K. 现在如果当前索引的总和是 (K + a) 那么我们知道子串总和,从所有那些总和是 (a) 的索引,直到当前索引将是 K,所以具有总和 (a) 的索引计数,将添加到结果中。这个过程用下面的例子来解释,

string s = “100101”
K = 2
prefix sum array = [1, 1, 1, 2, 2, 3]

So, at index 3,    we have prefix sum 2, 
Now total indices from where sum is 2, is 1
so result = 1

Substring considered = [“1001”]
At index 4,        we have prefix sum 2,
Now total indices from where sum is 2, is 
1 so result = 2

Substring considered = [“1001”, “10010”]
At index 5,     we have prefix sum 3,
Now total indices from where sum is 2, 
is 3 so result = 5
Substring considered = [“1001”, “10010”, 
“00101”, “0101”, “101”]

所以我们需要跟踪两件事,前缀和和特定和的频率。在下面的代码中,不是存储完整的前缀总和,而是仅使用存储在数组中的一个变量和总和频率来存储当前索引处的前缀总和。解决方案的总时间复杂度为 O(N)。

C++
// C++ program to find count of substring containing
// exactly K ones
#include 
using namespace std;
 
// method returns total number of substring having K ones
int countOfSubstringWithKOnes(string s, int K)
{
    int N = s.length();
    int res = 0;
    int countOfOne = 0;
    int freq[N + 1] = {0};
 
    // initialize index having zero sum as 1
    freq[0] = 1;
 
    // loop over binary characters of string
    for (int i = 0; i < N; i++) {
 
        // update countOfOne variable with value
        // of ith character
        countOfOne += (s[i] - '0');
 
        // if value reaches more than K, then
        // update result
        if (countOfOne >= K) {
 
            // add frequency of indices, having
            // sum (current sum - K), to the result
            res += freq[countOfOne - K];
        }
 
        // update freqency of one's count
        freq[countOfOne]++;
    }
    return res;
}
 
// Driver code to test above methods
int main()
{
    string s = "10010";
    int K = 1;
    cout << countOfSubstringWithKOnes(s, K) << endl;
    return 0;
}


Java
// Java program to find count of substring
// containing exactly K ones
import java.io.*;
 
public class GFG {
 
    // method returns total number of
    // substring having K ones
    static int countOfSubstringWithKOnes(
                            String s, int K)
    {
        int N = s.length();
        int res = 0;
        int countOfOne = 0;
        int []freq = new int[N+1];
     
        // initialize index having zero
        // sum as 1
        freq[0] = 1;
     
        // loop over binary characters
        // of string
        for (int i = 0; i < N; i++) {
     
            // update countOfOne variable
            // with value of ith character
            countOfOne += (s.charAt(i) - '0');
     
            // if value reaches more than
            // K, then update result
            if (countOfOne >= K) {
     
                // add frequency of indices,
                // having sum (current sum - K),
                // to the result
                res += freq[countOfOne - K];
            }
     
            // update freqency of one's count
            freq[countOfOne]++;
        }
         
        return res;
    }
     
    // Driver code to test above methods
    static public void main (String[] args)
    {
        String s = "10010";
        int K = 1;
         
        System.out.println(
            countOfSubstringWithKOnes(s, K));
    }
}
 
// This code is contributed by vt_m.


Python3
# Python 3 program to find count of
# substring containing exactly K ones
 
# method returns total number of
# substring having K ones
def countOfSubstringWithKOnes(s, K):
    N = len(s)
    res = 0
    countOfOne = 0
    freq = [0 for i in range(N + 1)]
 
    # initialize index having
    # zero sum as 1
    freq[0] = 1
 
    # loop over binary characters of string
    for i in range(0, N, 1):
         
        # update countOfOne variable with
        # value of ith character
        countOfOne += ord(s[i]) - ord('0')
 
        # if value reaches more than K,
        # then update result
        if (countOfOne >= K):
             
            # add frequency of indices, having
            # sum (current sum - K), to the result
            res += freq[countOfOne - K]
         
        # update freqency of one's count
        freq[countOfOne] += 1
     
    return res
 
# Driver code
if __name__ == '__main__':
    s = "10010"
    K = 1
    print(countOfSubstringWithKOnes(s, K))
 
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to find count of substring
// containing exactly K ones
using System;
 
public class GFG {
 
    // method returns total number of
    // substring having K ones
    static int countOfSubstringWithKOnes(
                           string s, int K)
    {
        int N = s.Length;
        int res = 0;
        int countOfOne = 0;
        int []freq = new int[N+1];
     
        // initialize index having zero
        // sum as 1
        freq[0] = 1;
     
        // loop over binary characters
        // of string
        for (int i = 0; i < N; i++) {
     
            // update countOfOne variable
            // with value of ith character
            countOfOne += (s[i] - '0');
     
            // if value reaches more than
            // K, then update result
            if (countOfOne >= K) {
     
                // add frequency of indices,
                // having sum (current sum - K),
                // to the result
                res += freq[countOfOne - K];
            }
     
            // update freqency of one's count
            freq[countOfOne]++;
        }
         
        return res;
    }
     
    // Driver code to test above methods
    static public void Main ()
    {
        string s = "10010";
        int K = 1;
         
        Console.WriteLine(
            countOfSubstringWithKOnes(s, K));
    }
}
 
// This code is contributed by vt_m.


PHP
= $K)
        {
 
            // add frequency of indices,
            // having sum (current sum - K),
            // to the result
            $res = $res + $freq[$countOfOne - $K];
        }
 
        // update freqency
        // of one's count
        $freq[$countOfOne]++;
    }
    return $res;
}
 
// Driver code
$s = "10010";
$K = 1;
echo countOfSubstringWithKOnes($s, $K) ,"\n";
 
// This code is contributed by m_kit
?>


Javascript


输出:

9

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程