Since s is a concatenation of anagrams of t, the frequency of each character in s must be a multiple of its frequency in t. The minimum possible length of t is the sum of the greatest common divisors (GCD) of the counts of each character in s.
classSolution {
public:int minAnagramLength(string s) {
vector<int> cnt(26);
for (char c : s) cnt[c-'a']++;
int g =0;
for (int x : cnt) if (x) g = gcd(g, x);
int ans =0;
for (int x : cnt) if (x) ans += x / g;
return ans;
}
intgcd(int a, int b) { return b ? gcd(b, a % b) : a; }
};
funcminAnagramLength(sstring) int {
cnt:= make([]int, 26)
for_, c:=ranges {
cnt[c-'a']++ }
g:=0gcd:=func(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna }
for_, x:=rangecnt {
ifx > 0 {
ifg==0 { g = x } else { g = gcd(g, x) }
}
}
ans:=0for_, x:=rangecnt {
ifx > 0 {
ans+=x/g }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintminAnagramLength(String s) {
int[] cnt =newint[26];
for (char c : s.toCharArray()) cnt[c-'a']++;
int g = 0;
for (int x : cnt) if (x > 0) g = gcd(g, x);
int ans = 0;
for (int x : cnt) if (x > 0) ans += x / g;
return ans;
}
privateintgcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminAnagramLength(s: String): Int {
val cnt = IntArray(26)
for (c in s) cnt[c-'a']++var g = 0fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
for (x in cnt) if (x > 0) g = if (g ==0) x else gcd(g, x)
var ans = 0for (x in cnt) if (x > 0) ans += x / g
return ans
}
}
1
2
3
4
5
6
7
defmin_anagram_length(s: str) -> int:
from math import gcd
from functools import reduce
from collections import Counter
cnt = Counter(s)
g = reduce(gcd, cnt.values())
return sum(x // g for x in cnt.values())
impl Solution {
pubfnmin_anagram_length(s: String) -> i32 {
letmut cnt = [0; 26];
for c in s.chars() {
cnt[c asusize-'a'asusize] +=1;
}
letmut g =0;
for&x in&cnt {
if x >0 {
g =if g ==0 { x } else { gcd(g, x) };
}
}
letmut ans =0;
for&x in&cnt {
if x >0 {
ans += x / g;
}
}
ans
}
}
fngcd(a: i32, b: i32) -> i32 {
if b ==0 { a } else { gcd(b, a % b) }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
minAnagramLength(s: string):number {
constcnt= Array(26).fill(0);
for (constcofs) cnt[c.charCodeAt(0) -97]++;
letg=0;
constgcd= (a: number, b: number):number=>b===0?a : gcd(b, a%b);
for (constxofcnt) if (x>0) g=g===0?x : gcd(g, x);
letans=0;
for (constxofcnt) if (x>0) ans+=x/g;
returnans;
}
}