696. Count Binary Substrings
作者:互联网
这道题,最重要的是要能观察出,连续的0和连续的1之间的关系——每一组连续的0和连续的1可以贡献出:Math.min(连续0,连续1)
下面的两个算法都可以beat 100%,时间复杂度O(n).
public int countBinarySubstrings(String s) { int res = 0; int cur = 1, pre = 0; char[] cs = s.toCharArray(); for (int i = 1; i < cs.length; i++) { if (cs[i] == cs[i - 1]) cur++; else { res += Math.min(pre, cur); pre = cur; cur = 1; } } return res + Math.min(pre, cur); }
public int countBinarySubstrings(String s) { int res = 0; int cur = 1, pre = 0; char[] cs = s.toCharArray(); for (int i = 1; i < cs.length; i++) { if (cs[i] == cs[i - 1]) cur++; else { pre = cur; cur = 1; } if (pre >= cur) res++; } return res; }
标签:Count,Binary,pre,cur,int,res,++,Substrings,cs 来源: https://www.cnblogs.com/feiflytech/p/15824900.html