본문 바로가기
Problem Solving/LeetCode

[LeetCode] 696. Count Binary Substrings - Java

by graycode 2026. 9. 25.

• 문제 링크

 

Count Binary Substrings - LeetCode

Can you solve this real interview question? Count Binary Substrings - Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively

leetcode.com

 

• 풀이 코드

public class Solution {

    public int countBinarySubstrings(String s) {
        int sum = 0, prev = 0, cur = 1;
        for (int i = 1, n = s.length(); i < n; i++) {
            if (s.charAt(i - 1) == s.charAt(i)) cur++;
            else {
                sum += Math.min(prev, cur);
                prev = cur;
                cur = 1;
            }
        }

        return sum + Math.min(prev, cur);
    }

}

댓글