Halo World

[LeetCode] 696. Count Binary Substrings 본문

스터디/알고리즘 문제풀이

[LeetCode] 696. Count Binary Substrings

_Yeony 2021. 10. 4. 10:22

https://leetcode.com/problems/count-binary-substrings/

//풀이 봄
class Solution {
    /*public int countBinarySubstrings(String s) {
        int[] groups = new int[s.length()];
        int idx = 0;
        groups[0]=1;
        for(int i=1;i<s.length(); i++){
            if(s.charAt(i-1) != s.charAt(i)) {
                groups[++idx]=1;
            } else {
                groups[idx]++;
            }
        }
        
        int ans = 0;
        for(int i=1;i<=idx;i++) {
            ans+=Math.min(groups[i-1], groups[i]);
        }
        return ans;
        
    }*/
    
    public int countBinarySubstrings(String s) {
        int result = 0, prev = 0, cur = 1;
        
        for(int i=1;i<s.length();i++){
            if(s.charAt(i-1)!=s.charAt(i)) {
                result += Math.min(prev, cur);
                prev = cur;
                cur = 1;
            } else {
                cur++;
            }
        }
        return result+Math.min(prev,cur);
        
    }
}