关于#c++#的问题:给定一个长度为n的01串,你需要选择一段任意长度(可以为0)的区间对其翻转,求最长的一段连续的全是1的区间的长度

img


这个用c++要咋写呀,如何求出最长一的长度,。;‘【】-=0987654332

效果如图 :

img

代码如下,如有帮助给个采纳

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

int maxConsecutiveOnes(string str) {
    int n = str.length();
    int maxLength = 0;
    int currentLength = 0;

    for (int i = 0; i < n; i++) {
        if (str[i] == '1') {
            currentLength++;
        } else {
            maxLength = max(maxLength, currentLength);
            currentLength = 0;
        }
    }

    maxLength = max(maxLength, currentLength);

    return maxLength;
}

int main() {
    int n;
    cout << "请输入二进制串的长度:";
    cin >> n;

    string binaryString;
    cout << "请输入二进制串(由0和1组成):";
    cin >> binaryString;

    int longestConsecutiveOnes = maxConsecutiveOnes(binaryString);
    
    cout << "未翻转时,最长连续1区间的长度为:" << longestConsecutiveOnes << endl;

    // 区间翻转
    int maxFlippedConsecutiveOnes = longestConsecutiveOnes; // 初始化为未翻转时的连续1区间长度
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            string temp = binaryString;
            for (int k = i; k <= j; k++) {
                temp[k] = (temp[k] == '0') ? '1' : '0';
            }
            
            // 更新翻转后的最长连续1区间长度
            maxFlippedConsecutiveOnes = max(maxFlippedConsecutiveOnes, maxConsecutiveOnes(temp));
        }
    }

    cout << "翻转后,最长连续1区间的长度为:" << maxFlippedConsecutiveOnes << endl;

    return 0;
}