当前位置:网站首页>696. Count binary substring

696. Count binary substring

2022-07-05 08:35:00 Mr Gao

696. Counting binary substrings

Given a string s, Count and return with the same number 0 and 1 Non empty of ( continuity ) Number of substrings , And all of these substrings 0 And all 1 They are continuous in groups .

Recurring ( Different positions ) The number of substrings should also be counted .

Example 1:

Input :s = “00110011”
Output :6
explain :6 The substring satisfies the same number of consecutive 1 and 0 :“0011”、“01”、“1100”、“10”、“0011” and “01” .
Be careful , Some repeated substrings ( Different positions ) Count the number of times they appear .
in addition ,“00110011” Not a valid substring , Because of all the 0( also 1 ) No combination .

Example 2:

Input :s = “10101”
Output :4
explain : Yes 4 Substring :“10”、“01”、“10”、“01” , Continuous with the same number 1 and 0 .

This problem is actually quite complicated , We need to do a lot of optimization :

int countBinarySubstrings(char * s){
    
    int zerocount=0,onecount=0;
    int i;
    int count=0;
    while(s[i]!='\0'){
    
        int j;
        for(j=i;s[j]!='\0';j++){
    
          // printf("--%d %d ",zerocount,onecount);
            if(s[j]=='0'){
    
                zerocount++;
                if(onecount!=0&&zerocount>onecount){
    
                    i=i+zerocount-onecount-2;

                    onecount=0;
                    zerocount=0;
                    break;
                }
                if(zerocount==onecount){
     
                    count=count+zerocount;
                       i=i+zerocount-1;
                      onecount=0;
                    zerocount=0;
                   
                    break;
                }

            }

             if(s[j]=='1'){
    
                onecount++;
                if(zerocount!=0&&onecount>zerocount){
    
                    i=i+onecount-zerocount-2;
                    onecount=0;
                    zerocount=0;
                    break;
                }
                if(zerocount==onecount){
    
                     count=count+zerocount;
                     i=i+zerocount-1;
                      onecount=0;
                    zerocount=0;
                   
                    break;
                }

            }
           
        }
          onecount=0;
         zerocount=0;
        i++;
    }
    return count;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050830330465.html