标签:hash sub head alt substr 图片 class long nbsp
class Solution { public: long mod = 100000000000007L; long head=1L; int distinctEchoSubstrings(string text) { int n=text.size(); unordered_set<long> st; for(int l=1;l<=n/2;++l){ head*=26L; head%=mod; int leftidx=0; int rightidx=l; long leftHash=initHash(text,0,l); long rightHash=initHash(text,l,l); if(leftHash==rightHash) st.insert(leftHash); leftidx++; rightidx++; while(rightidx+l<=n){ leftHash=reHash(leftHash,text,leftidx-1,leftidx+l-1); rightHash=reHash(rightHash,text,rightidx-1,rightidx+l-1); if(leftHash==rightHash) st.insert(leftHash); ++leftidx,++rightidx; } } return st.size(); } long initHash(string& text, int idx, int len){ long hash=0; for(int i=idx;i-idx+1<=len;++i){ hash=((hash*26L)%mod+text[i]-‘a‘+1)%mod; } return hash; } long reHash(long hash, string& text, int idx1, int idx2){ int add=text[idx2]-‘a‘+1; int sub=text[idx1]-‘a‘+1; hash=((hash*26L)%mod+add)%mod; hash=(hash-head*sub)%mod; hash=(hash+mod)%mod; return hash; } };
LC 1316. Distinct Echo Substrings
标签:hash sub head alt substr 图片 class long nbsp
原文地址:https://www.cnblogs.com/FEIIEF/p/12862173.html