Input: s ="1212"Output: 5Explanation: The substrings that meet the requirements are "1","2","12","21","1212".Note that although the substring "12" appears twice, it is only counted once.
Example 2:
1
2
3
Input: s ="12321"Output: 9Explanation: The substrings that meet the requirements are "1","2","3","12","23","32","21","123","321".
We can check all substrings and use a hash set to count unique ones where all digits appear the same number of times. For each substring, count digit frequencies and check if all nonzero counts are equal.
import java.util.*;
classSolution {
publicintequalDigitFrequency(String s) {
Set<String> set =new HashSet<>();
int n = s.length();
for (int i = 0; i < n; ++i) {
int[] cnt =newint[10];
for (int j = i; j < n; ++j) {
cnt[s.charAt(j) -'0']++;
int freq = 0;
boolean ok =true;
for (int c : cnt) {
if (c > 0) {
if (freq == 0) freq = c;
elseif (freq != c) { ok =false; break; }
}
}
if (ok) set.add(s.substring(i, j + 1));
}
}
return set.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defequalDigitFrequency(s):
seen = set()
n = len(s)
for i in range(n):
cnt = [0]*10for j in range(i, n):
cnt[int(s[j])] +=1 freq =0 ok =Truefor c in cnt:
if c >0:
if freq ==0:
freq = c
elif freq != c:
ok =Falsebreakif ok:
seen.add(s[i:j+1])
return len(seen)