[LeetCode] 1781. Sum of Beauty of All Substrings
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.
所有子字符串美丽值之和。
一个字符串的 美丽值 定义为:出现频率最高字符与出现频率最低字符的出现次数之差。
比方说,"abaacc" 的美丽值为 3 - 1 = 2 。
给你一个字符串 s ,请你返回它所有子字符串的 美丽值 之和。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-beauty-of-all-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题既然是返回所有子串的美丽值之和,那么起码应该是 O(n^2) 级别的复杂度,因为我们需要这个级别的复杂度把子串都找到,才能判断美丽值。所以这里我用两层 for 循环,找到子串,然后用一个长度为26的数组统计每个不同子串的美丽值。找的过程中,累加到结果集即可。
时间O(n^2) - counting sort 统计的复杂度几乎可以忽略不计
空间O(n)
Java实现
1 class Solution { 2 public int beautySum(String s) { 3 int res = 0; 4 for (int i = 0; i < s.length(); i++) { 5 int[] bucket = new int[26]; 6 for (int j = i; j < s.length(); j++) { 7 bucket[s.charAt(j) - 'a']++; 8 res += helper(bucket); 9 } 10 } 11 return res; 12 } 13 14 private int helper(int[] bucket) { 15 int min = Integer.MAX_VALUE; 16 int max = Integer.MIN_VALUE; 17 for (int i = 0; i < 26; i++) { 18 if (bucket[i] == 0) { 19 continue; 20 } 21 min = Math.min(min, bucket[i]); 22 max = Math.max(max, bucket[i]); 23 } 24 return max - min; 25 } 26 }