LeedCode刷题:696.计数二进制子串

解题思路:我们将二进制串按照字符分组,例如00111011可以分为{2,3,1,2}

我们只需看相邻的数字中,取min(u,v)即可,我们只要遍历所有相邻的数对,求它们的贡献总和,即可得到答案。

统计出个数后,

对于每个个数只关心它前面的值,所以使用last来存储前面的cnt,一次次将min加入结果中即可

 1 class Solution {
 2     public int countBinarySubstrings(String s) {
 3         int ptr=0;
 4         int ans=0;
 5         int last=0;
 6         int n=s.length();
 7         while(ptr<n){
 8             char c=s.charAt(ptr);
 9             int cnt=0;
10             while(ptr<n&&s.charAt(ptr)==c){
11                 ptr++;
12                 cnt++;//连续字符出现的次数
13             }
14             ans+=Math.min(last,cnt);//取最小值,即子串个数
15             last=cnt;
16         }
17         
18         
19         return ans;
20     }
21 }
原文地址:https://www.cnblogs.com/nilbook/p/13469224.html