Rely binary strings of size identical as given string after removing of substrings “01” and “00” that consists of at the least one ‘1’

by admin

Given a binary string S, the duty is to depend whole binary strings consisting of at the least one ‘1’ of size equal to the size of given string after repeatedly eradicating all occurrences of substrings “10” and “00” from the given string.

Examples:

Enter: S = “111”
Output: 7
Rationalization: Since there are not any occurrences of “10” or “01” within the given string, size of the remaining string is 3. All attainable binary strings of size Three consisting of at the least one set bit are {“001”, “010”, “011”, “100”, “101”, “110”, “111”}

Enter: S = “0101”
Output: 3
Rationalization: After deleting “10”, S = “01”. Subsequently, size of remaining string is 2. Strings of size 2 consisting of at the least one set bit are {“01”, “10”, “11”}

Method: The concept is to calculate the length of the given string after eradicating all substrings of the shape “10” and “00” from it. Contemplating the remaining ;size of the string to be N, the entire quantity strings consisting of at the least one set bit can be equal to 2N-1.

Comply with the beneath steps to unravel the issue:

  1. Initialize a variable, say depend .
  2. Iterate over the characters of the string S. For every character, test whether it is ‘0’ and depend is bigger than 0 or not. If discovered to be true, decrement the depend by 1.
  3. In any other case, if the present character is ‘1’, increment depend by 1.
  4. After full traversal of the string, print 2depend – 1 because the required reply.

 Beneath is the implementation of the above strategy:

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

void countString(string S)

{

    

    lengthy lengthy depend = 0;

  

    

    for (auto it : S) {

  

        if (it == '0' and depend > 0) {

            count--;

        }

        else {

            depend++;

        }

    }

  

    

    cout << ((1 << depend) - 1) << "n";

}

  

int major()

{

  

    

    string S = "1001";

  

    

    countString(S);

  

    return 0;

}

Time Complexity: O(L) the place L is the size of the string. 
Auxiliary Area: O(1)

Consideration reader! Don’t cease studying now. Pay money for all of the vital DSA ideas with the DSA Self Paced Course at a student-friendly worth and grow to be trade prepared.



If you happen to like GeeksforGeeks and want to contribute, you can even write an article utilizing contribute.geeksforgeeks.org or mail your article to [email protected] See your article showing on the GeeksforGeeks major web page and assist different Geeks.

Please Enhance this text if you happen to discover something incorrect by clicking on the “Enhance Article” button beneath.

Related Posts

Leave a Comment