Given a string s, you need to partition it into one or more balanced substrings. For example, if s == "ababcc" then ("abab", "c", "c"), ("ab", "abc", "c"), and ("ababcc") are all valid partitions, but ("a", **" bab"**, "cc"), (**" aba"**, "bc", "c"), and ("ab", **" abcc"**) are not.
The unbalanced substrings are bolded.
Return the minimum number of substrings that you can partition s into.
Note: A balanced string is a string where each character in the string occurs the same number of times.
Input: s ="fabccddg"Output: 3Explanation:
We can partition the string `s` into 3 substrings in one of the following
ways: `("fab, "ccdd", "g")`, or `("fabc", "cd", "dg")`.
We can greedily partition the string whenever the current substring can be balanced. For each substring, we count character frequencies and check if all nonzero counts are equal.
classSolution {
public:int minimumPartition(string s) {
int n = s.size(), ans =0, i =0;
while (i < n) {
vector<int> freq(26, 0);
for (int j = i; j < n; ++j) {
freq[s[j]-'a']++;
int cnt =0, val =0;
for (int f : freq) if (f) { if (!val) val = f; if (f != val) { val =-1; break; } cnt++; }
if (val >0) { ans++; i = j+1; break; }
}
}
return ans;
}
};
funcminimumPartition(sstring) int {
n, ans, i:= len(s), 0, 0fori < n {
freq:= make([]int, 26)
forj:=i; j < n; j++ {
freq[s[j]-'a']++cnt, val:=0, 0for_, f:=rangefreq {
iff > 0 {
ifval==0 { val = f }
iff!=val { val = -1; break }
cnt++ }
}
ifval > 0 {
ans++; i = j+1; break }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintminimumPartition(String s) {
int n = s.length(), ans = 0, i = 0;
while (i < n) {
int[] freq =newint[26];
for (int j = i; j < n; j++) {
freq[s.charAt(j)-'a']++;
int cnt = 0, val = 0;
for (int f : freq) if (f > 0) { if (val == 0) val = f; if (f != val) { val =-1; break; } cnt++; }
if (val > 0) { ans++; i = j+1; break; }
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funminimumPartition(s: String): Int {
val n = s.length
var ans = 0; var i = 0while (i < n) {
val freq = IntArray(26)
for (j in i until n) {
freq[s[j]-'a']++var cnt = 0; var val_ = 0for (f in freq) if (f > 0) { if (val_ ==0) val_ = f; if (f != val_) { val_ = -1; break }; cnt++ }
if (val_ > 0) { ans++; i = j+1; break }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defminimumPartition(self, s: str) -> int:
n, ans, i = len(s), 0, 0while i < n:
freq = [0]*26for j in range(i, n):
freq[ord(s[j])-97] +=1 vals = [f for f in freq if f]
if len(set(vals)) ==1:
ans +=1 i = j+1breakreturn ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnminimum_partition(s: String) -> i32 {
let n = s.len();
let s = s.as_bytes();
letmut ans =0; letmut i =0;
while i < n {
letmut freq = [0;26];
for j in i..n {
freq[(s[j]-b'a') asusize] +=1;
let vals: Vec<_>= freq.iter().filter(|&&f| f>0).collect();
if vals.iter().all(|&f|*f ==*vals[0]) {
ans +=1; i = j+1; break;
}
}
}
ans
}
}