给定二进制字符串中仅包含 1 的 K 个长度子数组的计数
给定一个二进制字符串str ,任务是找到仅包含1的K个长度子数组的计数。
例子:
Input: str = “0101000”, K=1
Output: 2
Explanation: 0101000 -> There are 2 subarrays with 1 ones
Input: str = “11111001”, K=3
Output: 3
方法:这个任务可以通过跟踪连续的组大小来解决。一旦我们得到groupSize ,我们可以推断出长度为k的可能子数组的数量,并且所有1都是groupSize – k + 1 。
请按照以下步骤解决问题:
- 从头开始迭代二进制字符串
- 增加计数,如果遇到1 ,并且在0出现的点。
- 存储当前计数得到连续1的groupSize,重新初始化计数为0。
- 使用关系groupSize – k + 1在此groupSize中添加大小为 k 的可能子数组的计数
- 返回计数的最终总和。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the count of all possible
// k length subarrays
int get(string s, int k)
{
// Add dummy character at last to handle
// edge cases, where string ends with '1'
s += '0';
int n = s.length();
int cnt = 0, ans = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '1')
cnt++;
else {
if (cnt >= k) {
ans += (cnt - k + 1);
}
cnt = 0;
}
}
return ans;
}
// Driver code
int main()
{
string str = "0101000";
int K = 1;
cout << get(str, K) << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find the count of all possible
// k length subarrays
static int get(String s, int k)
{
// Add dummy character at last to handle
// edge cases, where String ends with '1'
s += '0';
int n = s.length();
int cnt = 0, ans = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '1')
cnt++;
else {
if (cnt >= k) {
ans += (cnt - k + 1);
}
cnt = 0;
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String str = "0101000";
int K = 1;
System.out.print(get(str, K) +"\n");
}
}
// This code is contributed by Rajput-Ji
Python3
# Python code for the above approach
# Function to find the count of all possible
# k length subarrays
def get(s, k):
# Add dummy character at last to handle
# edge cases, where string ends with '1'
s += '0'
n = len(s)
cnt = 0
ans = 0
for i in range(n):
if (s[i] == '1'):
cnt += 1
else:
if (cnt >= k):
ans += (cnt - k + 1)
cnt = 0
return ans
# Driver code
str = "0101000"
K = 1
print(get(str, K))
# This code is contributed by Saurabh Jaiswal
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the count of all possible
// k length subarrays
static int get(string s, int k)
{
// Add dummy character at last to handle
// edge cases, where string ends with '1'
s += '0';
int n = s.Length;
int cnt = 0, ans = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '1')
cnt++;
else {
if (cnt >= k) {
ans += (cnt - k + 1);
}
cnt = 0;
}
}
return ans;
}
// Driver code
public static void Main()
{
string str = "0101000";
int K = 1;
Console.WriteLine(get(str, K));
}
}
// This code is contributed by ukasp.
Javascript
输出
2
时间复杂度: O(N)
辅助空间: O(1)