【Lintcode】1824. Most Frequent Substring

题目地址:

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)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/113926914
今日推荐