[LeetCode] 1781. Sum of Beauty of All Substrings
阿新 • • 發佈:2021-07-17
Thebeautyof 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 strings
, returnthe sum ofbeautyof 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 }