📜  通过拆分String,最多有K或(K+1)个子串和最多K个等于1的连续子串

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

通过拆分String,最多有K或(K+1)个子串和最多K个等于1的连续子串

给定一个长度为N的二进制字符串S和一个整数K ,任务是找到通过按以下条件拆分它可以获得的最大非重叠子字符串数:

  • 字符串的每个子字符串包含KK+11
  • 最多连续 K 个子串可以包含相同数量的 1

注意:如果字符串不包含KK + 1个 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)