题目
一个字符串的 美丽值 定义为:出现频率最高字符与出现频率最低字符的出现次数之差。
比方说,“abaacc” 的美丽值为 3 - 1 = 2 。
给你一个字符串 s ,请你返回它所有子字符串的 美丽值 之和
- 1 <= s.length <= 500
- s 只包含小写英文字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-beauty-of-all-substrings
解:
1.力扣第47场周赛第三题,想了很久用动态规划,或用别的方法。
2只能.暴力 两重遍历所有子串,数组统计字符解决(暴力大法好)
class Solution {
public int beautySum(String s) {
if (s.isEmpty()) {
return 0;
}
int totalSum = 0;
char[] chs = s.toCharArray();
for (int i = 0; i < chs.length; i++) {
int[] cnt = new int[26];
for (int j = i; j < chs.length; j++) {
cnt[chs[j] - 'a']++;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
//26大小,相对来说就是o(1)
for (int count : cnt) {
if (count > 0) {
max = Math.max(max, count);
min = Math.min(min, count);
}
}
totalSum = totalSum + max - min;
}
}
return totalSum;
}
}