一、Easy696 Count Binary Substrings
Input: "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Input: "10101" Output: 4 Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
解题思路:由于字符串是0和1相互交叉的,因此:
1.将s = "110001111000000"分成四个子字符串:group = {
}11
000
1111
000000
2.如果group[i] = 2, group[i+1]=3,那么两个组合起来,一定有11000或者是00111
3.类似于000111的情况,那么就有‘0’*3+‘1’*3,‘0’*2+‘1’*2,‘0’*1+‘1’*1,一共三种情况,因此如果group[i]和group[j]中的最小长度就是可以构成的个数
解题代码:
(1)(O(N) + O(1)) 注意groups[++t] = 1;和groups[t]++;的表示技巧。
public int countBinarySubstrings(String s) { int[] groups = new int[s.length()]; int t = 0; groups[0] = 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i-1) != s.charAt(i)) { groups[++t] = 1; } else { groups[t]++; } } int ans = 0; for (int i = 1; i <= t; i++) ans += Math.min(groups[i-1], groups[i]); return ans; }
(2)不用group数组而是直接使用两个int类型的数prev和curr来存储每个部分的长度
class Solution { public int countBinarySubstrings(String s) { int ans = 0, prev = 0, cur = 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i-1) != s.charAt(i)) { ans += Math.min(prev, cur); prev = cur; cur = 1; } else { cur++; } } return ans + Math.min(prev, cur); } }
二、