Simple Java Solution


  • 0
    A
    class Solution {
        public int countBinarySubstrings(String s) {
            int l = s.length(), ans = 0;
            char[] stc = s.toCharArray();
            for(int i=0;i<l-1;){
                char c = stc[i];
                if(c != stc[i+1]){// we got 01 or 10, increase ans by 1 and continue
                    ans++;
                    i++;
                    continue;
                }
                int curr = 1, j = i+1;
                while(j < l && stc[j] == c){
                    curr++;
                    j++;
                }
                int k = j, next = 0;
                while(j < l && stc[j] != c && next < curr){
                    next++;
                    j++;
                }
                ans += next;
                i = k;
                
            }
            
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.