Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum steps to remove substring 010 from a binary string in C++
Problem statement
Given a binary string, the task is to count the minimum steps to remove substring 010 from this binary string
Example
If input string is 010010 then 2 steps are required
- Convert first 0 to 1. Now string becomes 110010
- Convert last 0 to 1. Now final string becomes 110011
Algorithm
1. Iterate the string from index 0 sto n-2 2. If in binary string has consecutive three characters ‘0’, ‘1’, ‘0’ then any one character can be changed Increase the loop counter by 2
Example
#include <bits/stdc++.h>
using namespace std;
int getMinSteps(string str) {
int cnt = 0;
for (int i = 0; i < str.length() - 2; ++i) {
if (str[i] == '0' && str[i + 1] == '1' && str[i+ 2] == '0') {
++cnt;
i += 2;
}
}
return cnt;
}
int main() {
string str = "010010";
cout << "Minimum required steps = " << getMinSteps(str)
<< endl;
return 0;
}
When you compile and execute above program. It generates following output
Output
Minimum required steps = 2
Advertisements