forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
48 lines (38 loc) · 1.03 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// Source : https://leetcode.com/problems/count-binary-substrings/description/
/// Author : liuyubobobo
/// Time : 2017-10-15
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Time Complexity: O(len(s))
// Space Complexity: O(len(s))
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> cutRes = cut(s);
int res = 0;
for(int i = 0 ; i < cutRes.size()-1 ; i ++)
res += min(cutRes[i], cutRes[i+1]);
return res;
}
private:
vector<int> cut(string s){
vector<int> res;
int start = 0;
for(int i = start + 1; i <= s.size() ; )
if(i == s.size() || s[i] != s[start]){
res.push_back(i - start);
start = i;
i = start + 1;
}
else
i ++;
return res;
}
};
int main() {
cout << Solution().countBinarySubstrings("00110011") << endl;
cout << Solution().countBinarySubstrings("10101") << endl;
return 0;
}