|
| 1 | +// Source : https://leetcode.com/problems/sum-of-beauty-of-all-substrings/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-13 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * The beauty of a string is the difference in frequencies between the most frequent and least |
| 8 | + * frequent characters. |
| 9 | + * |
| 10 | + * For example, the beauty of "abaacc" is 3 - 1 = 2. |
| 11 | + * |
| 12 | + * Given a string s, return the sum of beauty of all of its substrings. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * Input: s = "aabcb" |
| 17 | + * Output: 5 |
| 18 | + * Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with |
| 19 | + * beauty equal to 1. |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: s = "aabcbaa" |
| 24 | + * Output: 17 |
| 25 | + * |
| 26 | + * Constraints: |
| 27 | + * |
| 28 | + * 1 <= s.length <= 500 |
| 29 | + * s consists of only lowercase English letters. |
| 30 | + ******************************************************************************************************/ |
| 31 | + |
| 32 | +class Solution { |
| 33 | +private: |
| 34 | + int beauty(string& s, int start, int end) { |
| 35 | + int stat[26] = {0}; |
| 36 | + for (int i=start; i<=end; i++){ |
| 37 | + stat[s[i]-'a']++; |
| 38 | + } |
| 39 | + int max = INT_MIN, min = INT_MAX; |
| 40 | + for (auto s: stat) { |
| 41 | + if (s == 0 ) continue; |
| 42 | + max = s > max ? s : max; |
| 43 | + min = s < min ? s : min; |
| 44 | + } |
| 45 | + return max - min; |
| 46 | + } |
| 47 | +public: |
| 48 | + int beautySum(string s) { |
| 49 | + return beautySum02(s); |
| 50 | + return beautySum01(s); |
| 51 | + } |
| 52 | + |
| 53 | + int beautySum01(string& s) { |
| 54 | + int sum = 0; |
| 55 | + for (int i=0; i<s.size()-1; i++) { |
| 56 | + for (int j=i+1; j<s.size(); j++) { |
| 57 | + sum += beauty(s, i, j); |
| 58 | + } |
| 59 | + } |
| 60 | + return sum; |
| 61 | + } |
| 62 | + |
| 63 | + //same as beautySum01(), but optimazed slightly |
| 64 | + int beautySum02(string& s) { |
| 65 | + int sum = 0; |
| 66 | + for (int i=0; i<s.size()-1; i++) { |
| 67 | + int stat[26] = {0}; |
| 68 | + for (int j=i; j<s.size(); j++) { |
| 69 | + stat[s[j]-'a']++; |
| 70 | + int max = INT_MIN, min = INT_MAX; |
| 71 | + for (auto& n: stat) { |
| 72 | + if (n <= 0 ) continue; |
| 73 | + max = n > max ? n : max; |
| 74 | + min = n < min ? n : min; |
| 75 | + } |
| 76 | + //cout << s.substr(i, j-i+1) << " --> "<< max << ":" << min << endl; |
| 77 | + sum += (max - min); |
| 78 | + } |
| 79 | + } |
| 80 | + return sum; |
| 81 | + } |
| 82 | +}; |
0 commit comments