LC 1316. Distinct Echo Substrings

Posted feiief

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 1316. Distinct Echo Substrings相关的知识,希望对你有一定的参考价值。

link

技术图片

 

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的主要内容,如果未能解决你的问题,请参考以下文章

1316. Distinct Echo Substrings

LeetCode 1316. Distinct Echo Substrings (RK哈希)

lc 115. Distinct Subsequences

[LC] 694. Number of Distinct Islands

[LC] 159. Longest Substring with At Most Two Distinct Characters

[LC] 78. Subsets