Simple O(N) Java solution!


  • 0
    T
    class Solution {
        public int countBinarySubstrings(String s) {
            if(s==null || s.length()<=1){
                return 0;
            }   
            char[] array = s.toCharArray();
            int sum = 0;
            char previousChar = array[0];
            int count = 1;
            int previous_count = 0;
            for(int i=1;i<array.length;i++){
                if(previousChar==array[i]){
                    count++;
                    if(previous_count>=count){
                        sum++;
                    }
                }else{
                    previous_count = count;
                    previousChar = array[i];
                    count = 1;
                    sum++;
                }
            }
            
            return sum;
        }
    }
    

Log in to reply
 

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