给定二进制字符串中仅包含 1 的 K 长度子数组的计数 |设置 2
给定二进制字符串str ,任务是找到仅包含1的K个长度子数组的计数。
例子
Input: str = “0101000”, K=1
Output: 2
Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s.
Input: str = “11111001”, K=3
Output: 3
方法:给定的问题也可以通过使用滑动窗口技术来解决。创建一个大小为K的窗口,初始计数为1秒,范围为 0到K-1 。然后从索引1到N-1遍历字符串并减去i-1的值并将i+K的值添加到当前计数。在这里,如果当前计数等于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)
{
int n = s.length();
int cntOf1s = 0;
for (int i = 0; i < k; i++)
if (s[i] == '1')
cntOf1s++;
int ans = cntOf1s == k ? 1 : 0;
for (int i = 1; i < n; i++) {
cntOf1s = cntOf1s - (s[i - 1] - '0')
+ (s[i + k - 1] - '0');
if (cntOf1s == k)
ans++;
}
return ans;
}
// Driver code
int main()
{
string str = "0110101110";
int K = 2;
cout << get(str, K) << endl;
return 0;
}
Java
// Java code to implement above approach
import java.util.*;
public class GFG {
// Function to find the count of all possible
// k length subarrays
static int get(String s, int k)
{
int n = s.length();
int cntOf1s = 0;
for (int i = 0; i < k; i++) {
if (s.charAt(i) == '1') {
cntOf1s++;
}
}
int ans = cntOf1s == k ? 1 : 0;
for (int i = 1; i < n; i++) {
if(i + k - 1 < n) {
cntOf1s = cntOf1s - (s.charAt(i - 1) - '0')
+ (s.charAt(i + k - 1) - '0');
}
if (cntOf1s == k)
ans++;
}
return ans;
}
// Driver code
public static void main(String args[])
{
String str = "0110101110";
int K = 2;
System.out.println(get(str, K));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code to implement above approach
# Function to find the count of all possible
# k length subarrays
def get(s, k):
n = len(s);
cntOf1s = 0;
for i in range(0,k):
if (s[i] == '1'):
cntOf1s += 1;
ans = i if (cntOf1s == k) else 0;
for i in range(1, n):
if (i + k - 1 < n):
cntOf1s = cntOf1s - (ord(s[i - 1]) - ord('0')) + (ord(s[i + k - 1]) - ord('0'));
if (cntOf1s == k):
ans += 1;
return ans;
# Driver code
if __name__ == '__main__':
str = "0110101110";
K = 2;
print(get(str, K));
# This code is contributed by 29AjayKumar
C#
// C# code to implement above approach
using System;
public class GFG {
// Function to find the count of all possible
// k length subarrays
static int get(string s, int k)
{
int n = s.Length;
int cntOf1s = 0;
for (int i = 0; i < k; i++) {
if (s[i] == '1') {
cntOf1s++;
}
}
int ans = cntOf1s == k ? 1 : 0;
for (int i = 1; i < n; i++) {
if (i + k - 1 < n) {
cntOf1s = cntOf1s - (s[i - 1] - '0')
+ (s[i + k - 1] - '0');
}
if (cntOf1s == k)
ans++;
}
return ans;
}
// Driver code
public static void Main()
{
string str = "0110101110";
int K = 2;
Console.WriteLine(get(str, K));
}
}
// This code is contributed by ukasp.
Javascript
输出
3
时间复杂度: O(N),其中 N 是字符串的长度。
辅助空间: O(1)。