leetcode.1781 所有子字符串美丽值之和 - 哈希表 + 双指针

1781. 所有子字符串美丽值之和

思路:

  • 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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值