在C++中删除二进制字符串中的“01”或“10”使其不包含“01”或“10”?
让我们首先声明初始字符串,计算其长度,并将它们传递给deleteSubstr(str,length)函数。
string str = "01010110011"; int length = str.length(); cout <<"Count of substring deletion"<< deleteSubstr(str, length);
在deleteSubstr(string str, int length)函数内部,for循环运行直到i小于length,并在遇到0和1时分别递增count_0和count_1变量。然后,该函数返回count_0和count_1的最小值。
int deleteSubstr(string str, int length){ int count_0 = 0, count_1 = 0; for (int i = 0; i < length; i++) { if (str[i] == '0') count_0++; else count_1++; } return min(count_0, count_1); }
示例
让我们看看以下删除二进制字符串中“01”或“10”使其不包含“01”或“10”的实现:
#include <iostream> using namespace std; int deleteSubstr(string str, int length){ int count_0 = 0, count_1 = 0; for (int i = 0; i < length; i++) { if (str[i] == '0') count_0++; else count_1++; } return min(count_0, count_1); } int main(){ string str = "01010110011"; int length = str.length(); cout <<"Count of substring deletion "<< deleteSubstr(str, length); return 0; }
输出
以上代码将产生以下输出:
Count of substring deletion 5
广告