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++)

Last updated

Was this helpful?