-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path696_leetcode_problem
More file actions
92 lines (74 loc) · 2.02 KB
/
696_leetcode_problem
File metadata and controls
92 lines (74 loc) · 2.02 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Solution {
public int countBinarySubstrings(String s) {
int n = s.length();
int prevGroup = 0;
int currGroup = 1;
int ans = 0;
for (int i = 1; i < n; i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
currGroup++;
} else {
ans += Math.min(prevGroup, currGroup);
prevGroup = currGroup;
currGroup = 1;
}
}
ans += Math.min(prevGroup, currGroup);
return ans;
}
}
in cpp with TLE example ****************************************************
// class Solution {
// public:
// bool check(int i , int j , string s ){
// int size = j-i+1;
// int count1= 0 ;
// int count2 = 0 ;
// for(int i = 0; i<size/2; i++){
// if(s[i]=='0'){
// count1++;
// }
// if(s[i]=='1'){
// count2++;
// }
// }
// if(count1 == size/2 || count2 == size/2){
// return true ;
// }
// return false ;
// }
// int countBinarySubstrings(string s) {
// int n = s.size();
// int ans = 0 ;
// for(int i = 0 ;i<n; i++){
// for(int j = i+1 ;j<n; i++){
// bool flag = check(i,j,s);
// if(flag){
// ans++;
// }
// }
// }
// return ans ;
// }
// };
class Solution {
public:
int countBinarySubstrings(string s) {
int n = s.size();
int prevGroup = 0;
int currGroup = 1;
int ans = 0;
for(int i = 1; i < n; i++){
if(s[i] == s[i-1]){
currGroup++;
}
else{
ans += min(prevGroup, currGroup);
prevGroup = currGroup;
currGroup = 1;
}
}
ans += min(prevGroup, currGroup);
return ans;
}
};