删除二进制字符串中的“01”或“10”以使其摆脱C++中的“01”或“10”?
让我们首先声明我们的初始字符串并计算其长度并将它们传递给deleteSubstr(str,length)函数。
string str = "01010110011"; int length = str.length(); cout <<"子串删除次数"<< deleteSubstr(str, length);
在deleteSubstr(stringstr,intlength)函数内部,for循环运行直到I小于长度并分别在遇到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输出结果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 <<"子串删除次数 "<< deleteSubstr(str, length); return 0; }
上面的代码将产生以下输出-
子串删除次数 5