题目链接:https://leetcode-cn.com/problems/distinct-echo-substrings/
思路:前缀字符串哈希
public class Solution {
int[] nextIndex = new int[2005];
long[] hashPre = new long[2005];
long[] hashPow = new long[2005];
HashSet<long> hasHash = new HashSet<long>();
public int DistinctEchoSubstrings(string text) {
int result = 0;
int[] lastPos = new int[256];
for (int i = 0; i < lastPos.Length; i++) {
lastPos[i] = -1;
}
for (int i = text.Length - 1; 0 <= i; i--) {
nextIndex[i] = lastPos[text[i]];
lastPos[text[i]] = i;
}
hashPow[0] = 1;
hashPre[0] = 0;
for (int i = 1; i <= text.Length; i++) {
hashPow[i] = hashPow[i - 1] * 31;
hashPre[i] = hashPre[i - 1] * 31 + text[i - 1];
}
for (int i = 0; i < text.Length; i++) {
int nextPos = i;
while (-1 != nextIndex[nextPos]) {
nextPos = nextIndex[nextPos];
int len = nextPos - i;
if (text.Length - nextPos < len) {
break;
}
long hash1 = hashPre[nextPos] - hashPre[i] * hashPow[len];
if (hasHash.Contains(hash1)) {
continue;
}
long hash2 = hashPre[nextPos + len] - hashPre[nextPos] * hashPow[len];
if (hash1 == hash2) {
result++;
hasHash.Add(hash1);
}
}
}
return result;
}
}