Skip to content

Commit 139d2de

Browse files
authored
Create 3399.Smallest-Substring-With-Identical-Characters-II.cpp
1 parent 8b35ff7 commit 139d2de

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class Solution {
2+
public:
3+
int minLength(string s, int numOps)
4+
{
5+
vector<int>arr;
6+
vector<int>nums;
7+
for (auto ch: s) nums.push_back(ch-'0');
8+
9+
int n = s.size();
10+
for (int i=0; i<n;)
11+
{
12+
int j = i;
13+
while (j<n && s[j]==s[i])
14+
j++;
15+
arr.push_back(j-i);
16+
i = j;
17+
}
18+
19+
int left = 1, right = n;
20+
while (left < right)
21+
{
22+
int mid = left + (right-left)/2;
23+
if (isOK(arr, nums, mid, numOps))
24+
right = mid;
25+
else
26+
left = mid+1;
27+
}
28+
return left;
29+
}
30+
31+
bool isOK(vector<int>arr, vector<int>&nums, int len, int numOps)
32+
{
33+
if (len==1)
34+
{
35+
int count = 0;
36+
for (int i=0; i<nums.size(); i++)
37+
count += (nums[i]==(i%2));
38+
if (count <= numOps)
39+
return true;
40+
41+
count = 0;
42+
for (int i=0; i<nums.size(); i++)
43+
count += (nums[i]!=(i%2));
44+
if (count <= numOps)
45+
return true;
46+
47+
return false;
48+
}
49+
50+
int count = 0;
51+
52+
for (int i=0; i<arr.size(); i++)
53+
{
54+
int x = arr[i];
55+
count += ceil((x-len)*1.0/(len+1));
56+
if (count>numOps)
57+
return false;
58+
}
59+
return true;
60+
}
61+
};

0 commit comments

Comments
 (0)