696. Count Binary Substrings

1.暴力æŗ•, 扞å‡ē所有 substring, then count 1's count equal 0's count, but 0,1是čĻé€ŖįēŒå‡ēįžįš„

å…ļå¯Ļįœ‹ 0 or 1 å‡ēįžįš„é€ŖįēŒčĄŒį‚ē

ex: 10101 ⇒ substring, 1010 ⇒ 不對喔īŧ 0 或 1 čĻ group é€ŖįēŒå‡ēįž

2. run length... å…ļå¯Ļ非常不åĨŊæƒŗ

Run Length

time: O(n)

space: O(1)

æ€čˇ¯

  1. s(i) = s(i-1) ⇒ åˆ¤æ–ˇæ˜¯åĻé€ŖįēŒä¸€æ¨Ŗ

  2. 不一æ¨Ŗįš„時候 ⇒ 1. 更新 pre, 2 更新 cur

ex : 0 0 1 1 ⇒ 到1 時, 不一æ¨Ŗäē†, 這時候 cur 還是 00,

do pre = cur

cur = 1

⇒ pre: 00, cur = 1

ex. 0011

hit the first '1'

when you hit the first '1', curRun = 1, preRun = 2,

means 0s number is larger than 1s number, so we could form "01" at this time, count++ .

hit the second '1',

When you hit the second '1', curRun = 2, preRun = 2,

means 0s' number equals to 1s' number, so we could form "0011" at this time, that is why count++)

class Solution {
    public int countBinarySubstrings(String s) {
        if (s == null || s.length() == 0) return 0;
        
        int res = 0;
        int prev = 0;
        int cur = 1;
        
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == s.charAt(i-1)) { // i from 1 
                cur++;
            } else {
                prev = cur;
                cur = 1;
            }
            if (prev >= cur) { // 這æ¨Ŗ可äģĨ計įŽ—到所有įš„įĩæžœ
                res++;
            }
        }
        return res;
    }
}

Last updated