日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

天池 在线编程 最频繁出现的子串(字符串哈希)

發(fā)布時間:2024/7/5 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 天池 在线编程 最频繁出现的子串(字符串哈希) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

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

子串的長度在之間 [minLength, maxLength]
子串的字符種類不超過 maxUnique
寫一個函數(shù) getMaxOccurrences ,其返回滿足條件的子串最多出現(xiàn)次數(shù)

輸入: s = "abcde" minLength = 2 maxLength = 5 maxUnique = 3 輸出: 1 說明:符合條件的子串有 `ab, bc, cd, de, abc, bcd, cde` 。 每一個子串只出現(xiàn)了一次,因此答案是 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 herepow.resize(27);pow[0] = 1;for(int i = 1; i <= 26; i++) {pow[i] = pow[i-1]*26;//預(yù)處理 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;//字符串哈希值,字符串個數(shù)unordered_map<char, int> m;//滑窗內(nèi)的字符計數(shù)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){ // 窗口內(nèi)子串字符種類滿足,長度達(dá)到 lenif(++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)//計數(shù) -1m.erase(s[j]);j++;}}} };

12ms C++

同題:LeetCode 1297. 子串的最大出現(xiàn)次數(shù)


我的CSDN博客地址 https://michael.blog.csdn.net/

長按或掃碼關(guān)注我的公眾號(Michael阿明),一起加油、一起學(xué)習(xí)進(jìn)步!

總結(jié)

以上是生活随笔為你收集整理的天池 在线编程 最频繁出现的子串(字符串哈希)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。