通过拆分String,最多有K或(K+1)个子串和最多K个等于1的连续子串
给定一个长度为N的二进制字符串S和一个整数K ,任务是找到通过按以下条件拆分它可以获得的最大非重叠子字符串数:
- 字符串的每个子字符串包含K或K+1个1 。
- 最多连续 K 个子串可以包含相同数量的 1
注意:如果字符串不包含K或K + 1个 1,则忽略该子字符串。
例子:
Input: S = “110101000010011011011011000100000”, K = 2
Output: 6
Explanation: The given string can be split into – [110], [10100], [00100110], [110], [110], [11000100000] so the answer is 6.
Input: S = “0000010001001100000110101100110000”, K = 2
Output: 5
Explanation: The given string can be split into – [000001000100], [1100000], [1101], [0110], [0110000] so the answer is 5.
Input: S = “11111111111”, K = 4
Output: 2
Explanation: The string can be split into [1111], [1111] and
The remaining string can be neglected because it does not contain K number of 1s.
方法:这个问题可以使用贪心方法来解决,它基于以下思想:
To maximize the count of substrings splitting such that as many substring have count of ‘1’ as K.
As it is not possible to split string having same number of ‘1’ successively more than K times, so after splitting K substrings with count of ‘1’ as K, split a substring with count of ‘1’ as K + 1.
按照以下步骤实施上述方法:
- 将字符串从i = 0 迭代到 N-1 :
- 继续将字符添加到当前子字符串中,直到 1s 的计数为K 。
- 如果连续的K个子串已经具有相同数量的子串,则向前移动并在当前子串中再添加一个 1 并开始一个新的子串。
- 增加子串数的计数。
- 如果不可能有K个 1,则忽略该子字符串。
- 返回子字符串的最终计数。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to check the number of 1's
// in the given string
int check(string s)
{
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1') {
count++;
}
}
return count;
}
// Function to find the minimum operations
// to make the array elements same
int MaxSplit(string s, int n, int k)
{
int times = 0;
int k2 = 0;
int ans = 0;
int y;
// Traversing the string
for (int i = 0; i < s.length(); i++) {
// Creating the substring
string x = s.substr(k2, i - k2);
// Checking the count of 1's in
// the substring
y = check(x);
// Checking whether the count of 1's
// equal to k
if (y == k) {
// If k successive substring
// with count of 1's equals to
// k are used then simply find
// 1 substring whose count of
// 1's is k+1
if (times == k) {
continue;
}
// Else add 1 to ans as we have
// the substring increase times.
else {
ans += 1;
k2 = i;
times++;
}
}
// If count of 1's is k+1 then
// split the string and add one
// to ans also set times to zero.
else if (y == k + 1) {
times = 0;
ans += 1;
k2 = i;
}
}
// Condition for checking whether
// we can take up the remaining string
if (y == k && y == k + 1 && y != 0) {
ans += 1;
}
return ans;
}
// Driver Code
int main()
{
string S = "11111111111";
int K = 4;
int N = S.length();
// Function call
cout << MaxSplit(S, N, K);
return 0;
}
2
时间复杂度: O(N 2 )
辅助空间: O(1)