forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1698.Number-of-Distinct-Substrings-in-a-String_v2.cpp
- Loading branch information
1 parent
c107334
commit 9abc5a9
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
...-of-Distinct-Substrings-in-a-String/1698.Number-of-Distinct-Substrings-in-a-String_v2.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
class Solution { | ||
public: | ||
int countDistinct(string s) | ||
{ | ||
int n = s.size(); | ||
long base = 26; | ||
long M = 1e9+9; | ||
int count = 1; | ||
long power = 1; | ||
long hash0 = 0; | ||
|
||
for (int len = 1; len <=n-1; len++) | ||
{ | ||
hash0 = (hash0 * base % M + s[len-1]-'a') % M; | ||
power = (power * base) % M; | ||
|
||
unordered_set<long>Set({hash0}); | ||
long hash = hash0; | ||
for (int i=len; i<n; i++) | ||
{ | ||
hash = (hash * base % M + (s[i]-'a')) % M; | ||
hash = (hash - power*(s[i-len]-'a') % M + M) %M ; | ||
Set.insert(hash); | ||
} | ||
count += Set.size(); | ||
} | ||
return count; | ||
} | ||
}; |