思路:
- i j 指针分别指向字符串两端
- i指针遍历每一个子字符串的起点 j指针紧接着i指针遍历以i为起点的字符串
- 哈希表统计每个子串的字符数 在cnt[s[i]] > 0的情况下 找出该子串字符最大和最小的值
- res累加每个子字符串的美丽值 mx-mi
1、c++
class Solution {
public:
int beautySum(string s)
{
int res=0,n=s.size();
int cnt[26];
for(int i=0;i<n;i++)
{
memset(cnt,0,sizeof cnt);
for(int j=i;j<n;j++)
{
cnt[s[j]-'a']++;
int minx=510,maxx=0;
for(int x:cnt)
if(x>0)
{
minx=min(minx,x);
maxx=max(maxx,x);
}
res+=maxx-minx;
}
}
return res;
}
};
2、java
class Solution {
public int beautySum(String s) {
int res=0,n=s.length();
for(int i=0;i<n;i++)
{
int[] cnt=new int[26];
for(int j=i;j<n;j++)
{
cnt[s.charAt(j)-'a']++;
int mx=0,mi=510;
for(int x:cnt)
if(x>0)
{
mx=Math.max(mx,x);
mi=Math.min(mi,x);
}
res+=mx-mi;
}
}
return res;
}
}