696. Counting Binary Strings
answer
This question has a hidden conclusion: from a string of the form 00111 or 11100, the number of strings that meet the requirements is Math.min(n,m), where n and m are the number of consecutive characters, such as n= in 000111111 3. m=6. And the continuous character sequence {1,3,2,3} is obtained, which means that if the string starts with 0, it is 011100111, and the number of strings that meet the requirements is min(1,3)+min(3,2)+min( 2,3)
class Solution {
public int countBinarySubstrings(String s) {
int ptr = 0, n = s.length(), last = 0, ans = 0;
while (ptr < n) {
char c = s.charAt(ptr);
int count = 0;
while (ptr < n && s.charAt(ptr) == c) {
++ptr;
++count;
}
ans += Math.min(count, last);
last = count;
}
return ans;
}
}