Given a string s, return the number ofdistinct substrings ofs.
A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.
Input: s ="aabbaba"Output: 21Explanation: The set of distinct strings is["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]
Example 2:
1
2
Input: s ="abcdefg"Output: 28
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
Follow up: Can you solve this problem in O(n) time complexity?
Every substring can be represented by its start and end indices. To count distinct substrings, insert all substrings into a trie or use a set of hashes. Trie is efficient for small n, rolling hash for larger n.
import java.util.*;
classTrie {
Trie[] next =new Trie[26];
}
classSolution {
publicintcountDistinct(String s) {
Trie root =new Trie();
int ans = 0, n = s.length();
for (int i = 0; i < n; ++i) {
Trie node = root;
for (int j = i; j < n; ++j) {
int c = s.charAt(j)-'a';
if (node.next[c]==null) {
node.next[c]=new Trie();
ans++;
}
node = node.next[c];
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classTrie { val next = Array<Trie?>(26) { null } }
classSolution {
funcountDistinct(s: String): Int {
val root = Trie()
var ans = 0for (i in s.indices) {
var node = root
for (j in i until s.length) {
val c = s[j]-'a'if (node.next[c] ==null) {
node.next[c] = Trie(); ans++ }
node = node.next[c]!! }
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defcountDistinct(self, s: str) -> int:
n = len(s)
seen = set()
for i in range(n):
for j in range(i+1, n+1):
seen.add(s[i:j])
return len(seen)