Skip to content

Commit 8e2bca3

Browse files
authored
Added task 1781.
1 parent 0d7c4bb commit 8e2bca3

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package g1701_1800.s1781_sum_of_beauty_of_all_substrings;
2+
3+
// #Medium #String #Hash_Table #Counting #2022_04_27_Time_38_ms_(100.00%)_Space_51.4_MB_(22.14%)
4+
5+
public class Solution {
6+
public int beautySum(String s) {
7+
int beauty = 0;
8+
for (int i = 0; i < s.length(); i++) {
9+
int[] numCountOfFreq = new int[s.length() + 1 - i];
10+
int[] charFreq = new int[26];
11+
charFreq[s.charAt(i) - 'a'] = 1;
12+
numCountOfFreq[1] = 1;
13+
int min = 1;
14+
int max = 1;
15+
for (int j = i + 1; j < s.length(); j++) {
16+
char c = s.charAt(j);
17+
charFreq[c - 'a']++;
18+
int freq = charFreq[c - 'a'];
19+
numCountOfFreq[freq - 1]--;
20+
numCountOfFreq[freq]++;
21+
if (numCountOfFreq[min] == 0) {
22+
min++;
23+
}
24+
if (min > freq) {
25+
min = freq;
26+
}
27+
if (max < freq) {
28+
max = freq;
29+
}
30+
beauty += max - min;
31+
}
32+
}
33+
return beauty;
34+
}
35+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
1781\. Sum of Beauty of All Substrings
2+
3+
Medium
4+
5+
The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
6+
7+
* For example, the beauty of `"abaacc"` is `3 - 1 = 2`.
8+
9+
Given a string `s`, return _the sum of **beauty** of all of its substrings._
10+
11+
**Example 1:**
12+
13+
**Input:** s = "aabcb"
14+
15+
**Output:** 5
16+
17+
**Explanation:** The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
18+
19+
**Example 2:**
20+
21+
**Input:** s = "aabcbaa"
22+
23+
**Output:** 17
24+
25+
**Constraints:**
26+
27+
* `1 <= s.length <= 500`
28+
* `s` consists of only lowercase English letters.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package g1701_1800.s1781_sum_of_beauty_of_all_substrings;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void beautySum() {
11+
assertThat(new Solution().beautySum("aabcb"), equalTo(5));
12+
}
13+
14+
@Test
15+
void beautySum2() {
16+
assertThat(new Solution().beautySum("aabcbaa"), equalTo(17));
17+
}
18+
}

0 commit comments

Comments
 (0)