- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Deletions of “01” or “10” in binary string to make it free from “01” or “10" in C++?
Let us first declare our initial string and calculate its length and pass them to the deleteSubstr(str,length) function.
string str = "01010110011"; int length = str.length(); cout <<"Count of substring deletion"<< deleteSubstr(str, length);
Inside of the deleteSubstr(string str, int length) function the for loop runs till I is less than length and increments the count_0 and count_1 variable on encounter of 0 and 1 respectively. The function then returns the min value of the count_0 and 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); }
Example
Let us see the following implementation of deletions of “01” or “10” in binary string to make it free from “01” or “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; }
Output
The above code will produce the following output −
Count of substring deletion 5
Advertisements