The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.
- For example, the beauty of
"abaacc"
is3 - 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.
Solution: Treemap
Time complexity: O(n2log26)
Space complexity: O(26)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Author: Huahua class Solution { public: int beautySum(string_view s) { const int n = s.size(); int ans = 0; vector<int> f(26); map<int, int> m; for (int i = 0; i < n; ++i) { fill(begin(f), end(f), 0); m.clear(); for (int j = i; j < n; ++j) { const int c = ++f[s[j] - 'a']; ++m[c]; if (c > 1) { auto it = m.find(c - 1); if (--it->second == 0) m.erase(it); } ans += rbegin(m)->first - begin(m)->first; } } return ans; } }; |