效果如图 :
代码如下,如有帮助给个采纳
#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;
}
class Solution {
public:
int jumpFloorII(int number) {
if(number==1)
{
return 1;
}
else{
return 2*jumpFloorII(number-1);
}
}
};