[LeetCode] Replace the Substring for Balanced String

1234. Replace the Substring for Balanced String

You are given a string containing only 4 kinds of characters ‘Q’, ‘W’, ‘E’ and ‘R’.

A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.

Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.

Return 0 if the string is already balanced.

Constraints:

  • 1 <= s.length <= 10^5
  • s.length is a multiple of 4
  • s contains only ‘Q’, ‘W’, ‘E’ and ‘R’.
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
class Solution {
bool isIncluded(map<char, int>& chars, const map<char, int>& mustIncluded, char exclude) {
for(auto entity : mustIncluded) {
if(entity.second > chars[entity.first] + (entity.first == exclude ? -1 : 0))
return false;
}
return true;
}
public:
int balancedString(string s) {
int limit = s.length() / 4;
map<char, int> m {{'Q', 0}, {'W', 0}, {'E', 0}, {'R', 0}};
for(int i = 0; i < s.length(); i++)
m[s[i]]++;
map<char, int> nonBalanced;
for(auto entity : m)
if(entity.second > limit)
nonBalanced.insert({entity.first, entity.second - limit});

if(nonBalanced.empty())
return 0;

int res = s.length();
int start = 0, end = s.length() - 1;
bool isBackward = false;

while(true) {
if(!isBackward) {
if(isIncluded(m, nonBalanced, s[start])) {
m[s[start]]--;
start++;
res = min(res, end - start + 1);
} else {
isBackward = true;
}
} else {
if(isIncluded(m, nonBalanced, s[end])) {
m[s[end]]--;
end--;
res = min(res, end - start + 1);
} else if(!start) {
return res;
} else {
m[s[start - 1]]++;
start--;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/08/PS/LeetCode/replace-the-substring-for-balanced-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.