给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。
重复出现的子串要计算它们出现的次数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-binary-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先统计连续的0和1分别有多少个,如:111100011000,得到4323;在4323中的任意相邻两个数字,取小的一个加起来,就是3+2+2 = 7.
class Solution {
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/count-binary-substrings/solution/ji-shu-er-jin-zhi-zi-chuan-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
优化空间复杂度
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);
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/count-binary-substrings/solution/ji-shu-er-jin-zhi-zi-chuan-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
利用类似回文字符串的解法
先找到中心轴(01, 10),然后找连续个数
public int countBinarySubstrings(String s) {
int result = 0;
char[] chars = s.toCharArray();
for(int i = 1; i < s.length(); i++){
int left = i - 1, right = i;
char leftChar = chars[left], rightChar = chars[right];
if(leftChar == rightChar)
continue;
while(left >= 0 && right < s.length() && chars[left] == leftChar && chars[right] == rightChar){
left--;
right++;
result++;
}
}
return result;
}
作者:ustcyyw
链接:https://leetcode-cn.com/problems/count-binary-substrings/solution/696java-zhong-xin-kuo-zhan-yu-hui-wen-chuan-xiang-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度O(n+k) 空间复杂度O(1)