Home > Net >  Print all the substrings with equal number of zeros and ones, But am not able to
Print all the substrings with equal number of zeros and ones, But am not able to

Time:03-08

I want to print all the substrings to be printed and everysubstring should have equal number of zeros and ones.I have strated the loop where i points to the index and initially number of zeros and one is equal to 0 and loop runs till both of them becomes equal and i push that in the vector. But My code is not running good . I am given enough time to figure out what could be the error but am not able to find.

Output

0 1 0 0 1 1 0 1 0 1  

Expected Output

01 0011 01 01

I am not able figure out the error , Please help me with this.

 #include <iostream>
#include <vector>
using namespace std;
vector<string> maxSubStr(string s, int n)
{
    vector<string> v;
    for (int i = 0; i < n; i  )
    {
        int ones = 0;
        int zeros = 0;
        int j = 0;
        for (j = i; zeros != ones && j<n; j  )
        {
            if (s[j] == '0')
            {
                zeros  ;
            }
            else
            {
                ones  ;
            }
        }
        if (zeros == ones)
        {
            int size = j - i;
            v.push_back(s.substr(i, size));
        }
        if(j==n){
            break;
        }
        i = j ;
    }
    return v;
}
int main()
{
    string str = "0100110101";
    int n = str.length();
    vector<string> v;
    v = maxSubStr(str, n);
    vector<string>::iterator it;
    for (it = v.begin(); it != v.end(); it  )
    {
        cout << *it << " ";
    }
    return 0;
}

CodePudding user response:

There are a number of little mistakes in your code. You should learn to use a debugger to step through it, the errors would become evident.

In the loop over i it is useless to set the value of j just before setting in again in the loop over j.Then, the loop should be limited by j<n to prevent an access past end of string. Next, you do not want to test s[i] but s[j]. Finally, the test zeros == ones should be in the j loop and should set i to the next position, that is j 1. Code could become:

vector<string> maxSubStr(string s)
{
    vector<string> v;
    int n = s.size();
    for (int i = 0; i < n; i  )
    {
        int ones = 0;
        int zeros = 0;
        int j = 0;
        for (j = i; j < n; j  )
        {
            if (s[j] == '0')
            {
                zeros  ;
            }
            else
            {
                ones  ;
            }
            if (zeros == ones)
            {
                v.push_back(s.substr(i, j   1 - i));
                i = j;
                break;
            }
        }
    }
    return v;
}
  • Related