力扣题-12.6
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:696. 计数二进制子串
解题思想:先统计连续的0和连续的1的个数,然后进行相加即可(想不到一点)
class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
count = []
temp = s[0]
num = 1
for i in range(1,len(s)):
if s[i]==temp:
num +=1
else:
count.append(num)
temp = s[i]
num = 1
count.append(num)
result = 0
for i in range(1,len(count)):
result += min(count[i],count[i-1])
return result
class Solution {
public:
int countBinarySubstrings(string s) {
std::vector<int> count;
char temp = s[0];
int num = 1;
for (int i = 1; i < s.length(); ++i) {
if (s[i] == temp) {
num += 1;
} else {
count.push_back(num);
temp = s[i];
num = 1;
}
}
count.push_back(num);
int result = 0;
for (int i = 1; i < count.size(); ++i) {
result += std::min(count[i], count[i - 1]);
}
return result;
}
};