给定一个字符串 s
,返回 s
的不同子字符串的个数。
字符串的 子字符串 是由原字符串删除开头若干个字符(可能是 0 个)并删除结尾若干个字符(可能是 0 个)形成的字符串。
示例 1:
输入:s = "aabbaba" 输出:21 解释:不同子字符串的集合是 ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]
示例 2:
输入:s = "abcdefg" 输出:28
提示:
1 <= s.length <= 500
s
由小写英文字母组成。
进阶:你可以以 O(n)
时间复杂度解决此问题吗?
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)
}