Skip to content

Commit 09039ae

Browse files
authored
Create replace-the-substring-for-balanced-string.cpp
1 parent 4f73731 commit 09039ae

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int balancedString(string s) {
7+
unordered_map<int, int> count;
8+
for (const auto& c : s) {
9+
++count[c];
10+
}
11+
int result = s.length();
12+
int left = 0;
13+
for (int right = 0; right < s.length(); ++right) {
14+
--count[s[right]];
15+
while (left < s.length() &&
16+
all_of(count.cbegin(), count.cend(),
17+
[&s](const auto& kvp) {
18+
return kvp.second <= s.length() / 4;
19+
})) {
20+
result = min(result, right - left + 1);
21+
++count[s[left++]];
22+
}
23+
}
24+
return result;
25+
}
26+
};

0 commit comments

Comments
 (0)