Give a string s
, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example:
Input: "00110011"
Output: 6
Approach:
C++
#include <bits/stdc++.h>using namespace std;int countBinarySubstrings(string s){//if string is empty then return 0if (s.empty()){return 0;}bool lastZero = false;if (s[0] == '0')lastZero = true;int zero_count = 0;int one_count = 0;int count = 0;for (int i = 0; i < s.size(); i++){//if zeroif (s[i] == '0'){//if last zero is false then//reset zero countif (lastZero == false){zero_count = 0;}//increment zero countzero_count++;//if one count is greater than 0//then decrement one count and update//the countif (one_count > 0){--one_count;count++;}lastZero = true;}//if oneelse{if (lastZero == true){one_count = 0;}one_count++;if (zero_count){--zero_count;count++;}lastZero = false;}}return count;}int main(){string str = "00110011";cout << countBinarySubstrings(str);return 0;}
No comments:
Post a Comment