696. Count Binary Substrings
https://leetcode.com/problems/count-binary-substrings/
Python
Two Pointer
列表如下
String | Group Count | Groups | Details |
---|---|---|---|
0011 | 2 | 01, 0011 | 1個group,min(0,1) = 2 |
00011 | 2 | 01, 0011 | 1個group,min(0,1) = 2 |
10101 | 4 | 10, 01, 10, 01 | 4個group,min(0,1)各別為1 |
000111 | 3 | 000111, 0011, 01 | 1個group,min(0,1) = 3 |
00011100111 | 7 | 000111, 0011, 01, 1100, 10, 0011, 01 | 3個group,min(0,1)各為3, 2, 2 |
歸納後會發現,以連續的0跟1組成的group,取其中各group小的數字加總為答案
class Solution:
def countBinarySubstrings(self, s: str) -> int:
left, right = 0, 1
count = 0
for i in range(1, len(s)):
if s[i] != s[i-1]:
count += min(left, right)
left = right
right = 1
else:
right += 1
count += min(left, right)
return count
JS
var countBinarySubstrings = function(s) {
let curr = 1;
let prev = 0;
let sum = 0;
for (let i = 1; i < s.length; i++) {
if (s[i] === s[i - 1]) curr++;
else {
sum += Math.min(curr, prev);
prev = curr;
curr = 1;
}
}
return sum + Math.min(curr, prev)
};