由数字0和1组成的字符串,最多将0变化k次产生的全1子串的最大长度

题目描述:给定一个由字符0和1组成的字符串;给定一个整数k,表示最多可以将原字符串中0变成1的次数;

问题:求改变后的字符串中,全1子串的最大长度。

c++代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int MaxSubLen(string str);
int MaxNum(int k, string str);
int main()
{
    int k;//最大可把0编程1的次数
    string str;//从键盘输入一个01交错的字符串
    int count=0;
    cin >> k;
    cin >> str;
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == '0')
            count++;
    }
    if (count <= k)
    {
        cout << "字符串:" << str << endl;
        cout << "变化" << k << "次可以变换成最大长度为:" << str.size() << endl;
    }
    else
    {
        cout << "字符串:" << str << endl;
        cout << "变化" << k << "次可以变换成最大长度为:" << MaxNum(k, str) << endl;
        return 0;
    }
}

int MaxSubLen(string str)
{
    int maxlen=0;
    vector<int> vecInt(str.length());
    vecInt[0] = 1;
    for (int i = 1; i < str.length(); i++)
    {
        if ((str[i] == '1') && (str[i] == str[i - 1]))
            vecInt[i] = vecInt[i - 1] + 1;
        else
            vecInt[i] = 1;
    }
    maxlen=*max_element(vecInt.begin(), vecInt.end());
    return maxlen;
}
int MaxNum(int k, string str)
{
    string referStr = str;
    int flag = 0;
    int max = 0;
    vector<int> maxVec;//用来存放每一个可能产生最大长度的可疑最大长度
    int result = 0;
    int j = 0;
    vector<int> indexVec;//用来存放每一个比较回合字符0的下标
    for (int i = 0; i < referStr.length();i++)
    {
        if (referStr[i] == '1')
        {
            ;
            //continue;
                    }
        else if (referStr[i] == '0')
        {
            
            //indexVec.resize(k);
            indexVec.push_back(i);
            flag++;
            if (flag < k)
            {
                referStr[i] = '1';
            }
            else if(flag==k)
            {
                referStr[i] = '1';
                max = MaxSubLen(referStr);
                maxVec.push_back(max);
                flag = 0;
                referStr = str;
                i = indexVec[1+j]-1;
                //indexVec.erase(indexVec.begin(),indexVec.end());
                j += k;//引入j的目的是为了遍历回溯
            }
        }
    }
    result = *max_element(maxVec.begin(),maxVec.end());
    return result;
}

测试结果:

6
10000001000010111001010
字符串:10000001000010111001010
变化6次可以变换成最大长度为:12
请按任意键继续. . .

原文地址:https://www.cnblogs.com/huster666/p/7479313.html