My accepted Java solution


  • 0
    S
    public int countBinarySubstrings(String s) {
        if(s.isEmpty()) return 0;
        int len = s.length();
        int res = 0;
        for(int i = 0; i < len; i++) {
            int countOne = s.charAt(i) == '1' ? 1 : 0;
            int countZero = s.charAt(i) == '0' ? 1 : 0;
            boolean isFlipped = false;
            for(int j = i + 1; j < len; j++) {
                countOne += (s.charAt(j) == '1' ? 1 : 0);
                countZero += (s.charAt(j) == '0' ? 1 : 0);
                if(s.charAt(j) != s.charAt(j - 1) && isFlipped) {
                    break;
                }
                if(s.charAt(j) != s.charAt(j - 1) && !isFlipped) {
                    isFlipped = true;
                }
                if(countOne == countZero) {
                    res++;
                }
            }
        }
        return res;
    }
    

Log in to reply
 

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