LeetCode 1316. Distinct Echo Substrings (RK哈希)

题意:

给一个字符串 寻找字符串为(a+a)格式的子串有多少。a+a 格式字符串比如 abcabc, ee 等。

首先O(N^2)枚举子串,然后通过哈希在O(1)复杂度判断子串是否符合要求。

RK哈希,Rabin_Karp 哈希,通过比较hash值是否相等来比较每个字符串是否相等。有概率出错(很小)

将字符串看做一个 n 进制的数字,通过一个大质数(如 1000000007 )取模,取得字符串的值。

这里使用无符号 64 位整数来存储哈希值,并通过 C++ 自然溢出的处理方式来取模。

因为有26个字母,选择27进制。注意一点是27进制,'a'不能被视为 0 否则 aa 和 a 就相同了。。。

代码:

class Solution {
public:
    int distinctEchoSubstrings(string text) {
        typedef unsigned long long ull;
        int n = text.size();
        int base = 27;
        vector<vector<ull>> h(n, vector<ull>(n));
        for (int i = 0; i < n; i++) {
            h[i][i] = text[i] - 'a' + 1;
            for (int j = i + 1; j < n; j++) {
                h[i][j] = h[i][j - 1] * base + (text[j] - 'a' + 1);
            }
        }
        set<ull> st;
        for (int i = 0; i < n; i++) {
            for (int j = 1; i + j * 2 <= n; j++) {
                if (h[i][i + j - 1] == h[i + j][i + j * 2 - 1]) {
                    st.insert(h[i][i + j - 1]);
                }
            }
        }
        return st.size();
    }
};

参考:

https://www.acwing.com/solution/leetcode/content/7499/

原文地址:https://www.cnblogs.com/wenruo/p/12250431.html