Given a string s
, return the number of distinct substrings of s
.
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.
Example 1:
Input: s = "aabbaba" Output: 21 Explanation: 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:
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?
class Solution:
def countDistinct(self, s: str) -> int:
n = len(s)
return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)})
class Solution {
public int countDistinct(String s) {
Set<String> ss = new HashSet<>();
int n = s.length();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j <= n; ++j) {
ss.add(s.substring(i, j));
}
}
return ss.size();
}
}
class Solution {
public:
int countDistinct(string s) {
unordered_set<string_view> ss;
int n = s.size();
string_view t, v = s;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j <= n; ++j) {
t = v.substr(i, j - i);
ss.insert(t);
}
}
return ss.size();
}
};
func countDistinct(s string) int {
ss := map[string]bool{}
for i := range s {
for j := i + 1; j <= len(s); j++ {
ss[s[i:j]] = true
}
}
return len(ss)
}