【Lintcode】1824. Most Frequent Substring

该博客介绍了一种算法,用于解决给定字符串中,在指定长度范围内且字符种类不超过特定数量的子串的最大出现次数问题。算法使用哈希表记录字符出现次数,并利用字符串哈希快速计算子串出现次数,时间复杂度为O(ls),空间复杂度为O(ls−m)。
摘要由CSDN通过智能技术生成

题目地址:

https://www.lintcode.com/problem/most-frequent-substring/description

给定一个字符串,问长度在 [ m , M ] [m,M] [m,M]区间内并且字符种类不超过 u u u的子串的最多出现次数。

M M M这个输入是没用的,因为如果一个长度更长的子串出现了 k k k次,那么长度是 m m m的子串必然能出现不少于 k k k次。所以我们只需要考虑长度 m m m的子串即可。可以用一个数组当哈希表记录每个字符出现次数,并且用字符串哈希来快速判断某个子串出现了多少次。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    /**
     * @param s: string s
     * @param minLength: min length for the substring
     * @param maxLength: max length for the substring
     * @param maxUnique: max unique letter allowed in the substring
     * @return: the max occurrences of substring
     */
    public int getMaxOccurrences(String s, int minLength, int maxLength, int maxUnique) {
        // write your code here
        if (minLength > s.length()) {
            return 0;
        }
        
        Map<Long, Integer> map = new HashMap<>();
        int[] count = new int[26];
        long hash = 0, P = 131, pow = 1;
        for (int i = 0; i < minLength; i++) {
            hash = hash * P + s.charAt(i);
            pow *= P;
            count[s.charAt(i) - 'a']++;
        }
    
        if (check(count, maxUnique)) {
            map.put(hash, 1);
        }
        
        int res = map.getOrDefault(hash, 0);
        for (int i = minLength; i < s.length(); i++) {
            hash = hash * P + s.charAt(i);
            hash -= s.charAt(i - minLength) * pow;
            count[s.charAt(i) - 'a']++;
            count[s.charAt(i - minLength) - 'a']--;
            if (check(count, maxUnique)) {
                map.put(hash, map.getOrDefault(hash, 0) + 1);
                res = Math.max(res, map.get(hash));
            }
        }
        
        return res;
    }
    
    private boolean check(int[] count, int maxUnique) {
        int dif = 0;
        for (int i : count) {
            if (i > 0) {
                dif++;
                if (dif > maxUnique) {
                    return false;
                }
            }
        }
        
        return true;
    }
}

时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( l s − m ) O(l_s-m) O(lsm)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值