版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85217814
Title:Count Binary Substrings 696
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/count-binary-substrings/
1. 求连续的0或者1的个数,将其存放到数组中,依次叠加相邻数中较小的
时间复杂度:O(n),两次一层for循环。
空间复杂度:O(n),申请了s.length()长度的数组。
/**
* 求连续的0或者1的个数,将其存放到数组中,依次叠加相邻数中较小的
* @param s
* @return
*/
public static int countBinarySubstrings(String s) {
int count[] = new int[s.length()];
int index = 0;
count[0] = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) != s.charAt(i)) {
count[++index] = 1;
}
else {
count[index]++;
}
}
int result = 0;
for (int i = 1; i < count.length; i++) {
result += Math.min(count[i - 1], count[i]);
}
return result;
}
2. 每次遍历是计算好,不行存放数组中,但是需要注意最后一次
时间复杂度:O(n),一次一层for循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 每次遍历是计算好,不行存放数组中,但是需要注意最后一次
* @param s
* @return
*/
public static int countBinarySubstrings1(String s) {
int pre = 0;
int cur = 1;
int result = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) != s.charAt(i)) {
result += Math.min(pre, cur);
pre = cur;
cur = 1;
}
else {
cur++;
}
}
return result + Math.min(pre, cur);
}