1. 程式人生 > 其它 >天池 線上程式設計 最頻繁出現的子串(字串雜湊)

天池 線上程式設計 最頻繁出現的子串(字串雜湊)

技術標籤:LintCode及其他OJ

文章目錄

1. 題目

給定一個字串,我們想知道滿足以下兩個條件的子串最多出現了多少次:

子串的長度在之間 [minLength, maxLength]
子串的字元種類不超過 maxUnique
寫一個函式 getMaxOccurrences ,其返回滿足條件的子串最多出現次數

輸入: 
s = "abcde"
minLength = 2
maxLength = 5
maxUnique = 3
輸出: 1
說明:符合條件的子串有 `ab, bc, cd, de, abc, bcd, cde` 。
每一個子串只出現了一次,因此答案是 1

https://tianchi.aliyun.com/oj/231203672248052266/245580596369363584

2. 解題

class Solution {
public:
    /**
     * @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
     */
int maxcount = 0; vector<long long> pow; int getMaxOccurrences(string &s, int minLength, int maxLength, int maxUnique) { // write your code here pow.resize(27); pow[0] = 1; for(int i = 1; i <= 26; i++) { pow[i] = pow[i-1]*26;//預處理 26 的冪次方
} for(int len = minLength; len <= maxLength; len++) { // 暴力列舉子串長度 help(s, len, maxUnique); } return maxcount; } void help(string &s, int len, int maxUnique) { unordered_map<long long, int> count;//字串雜湊值,字串個數 unordered_map<char, int> m;//滑窗內的字元計數 int i = 0; long long hash = 0; for( ; i < len-1; i++) { m[s[i]]++; hash = hash*26+s[i]-'a'; } for(int j = 0 ; i < s.size(); ++i) { m[s[i]]++; hash = hash*26+s[i]-'a'; if(m.size() <= maxUnique && i-j+1 == len) { // 視窗內子串字元種類滿足,長度達到 len if(++count[hash] > maxcount) maxcount = count[hash]; } while(i-j+1 > len || m.size() > maxUnique) { // 長度超了,或者 字元種類超了 hash -= pow[i-j]*(s[j]-'a');//最前面的字元雜湊值減去 if(--m[s[j]] == 0)//計數 -1 m.erase(s[j]); j++; } } } };

12ms C++

同題:LeetCode 1297. 子串的最大出現次數


我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明