LeetCode 1781. Sum of Beauty of All Substrings Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1781. Sum of Beauty of All Substrings

Description

The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.

  • For example, the beauty of "abaacc" is 3 - 1 = 2.

Given a string s, return the sum of beauty of all of its substrings.

 

Example 1:

Input: s = "aabcb"
Output: 5
Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.

Example 2:

Input: s = "aabcbaa"
Output: 17

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

Solutions

Solution 1: Enumeration + Counting

Enumerate the starting position i of each substring, find all substrings with the character at this starting position as the left endpoint, then calculate the beauty value of each substring, and accumulate it to the answer.

The time complexity is O(n2 × C), and the space complexity is O(C). Here, n is the length of the string, and C is the size of the character set. In this problem, C = 26.

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def beautySum(self, s: str) -> int: ans, n = 0, len(s) for i in range(n): cnt = Counter() for j in range(i, n): cnt[s[j]] += 1 ans += max(cnt.values()) - min(cnt.values()) return ans(code-box)

Solution 2

PythonJavaC++GoJavaScript
class Solution: def beautySum(self, s: str) -> int: ans, n = 0, len(s) for i in range(n): cnt = Counter() freq = Counter() mi = mx = 1 for j in range(i, n): freq[cnt[s[j]]] -= 1 cnt[s[j]] += 1 freq[cnt[s[j]]] += 1 if cnt[s[j]] == 1: mi = 1 if freq[mi] == 0: mi += 1 if cnt[s[j]] > mx: mx = cnt[s[j]] ans += mx - mi return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !