Easy-understanding Java Solution


  • 0
    P

    The idea is iterate the array once. For each character, it may contribute one to count or not. We use an Integer total to act as a stack. When the next character is the same with current one, plus one on total. Otherwise we subscribe one until total equals to 0. We use a flag to indicate whether all the 0's and all the 1's in current substrings are grouped consecutively.

    public int countBinarySubstrings(String s) {
            int res = 0;
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                int total = 1;
                boolean flag = false;
                for(int j = i + 1; j < s.length(); j++) {
                    if(s.charAt(j) == c){
                        if(flag)
                            break;
                        total += 1;
                    }
                    else{
                        total -= 1;
                        flag = true;
                        if(total == 0){
                            res += 1;
                            break;
                        }
                    }
                }
            }
            return res;
        }
    

Log in to reply
 

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