【发布时间】:2015-06-13 13:11:43
【问题描述】:
给定一个字符串和一个固定长度 l,我如何计算长度为 l 的不同子字符串的数量? 字符集的大小也是已知的。 (记为 s) 例如,给定一个字符串“PccjcjcZ”,s = 4,l = 3, 那么有5个不同的子字符串: “个人计算机”; “ccj”; “cjc”; “jcj”; “jcZ”
我尝试使用哈希表,但速度仍然很慢。 实际上我不知道如何使用字符大小。 我做过这样的事情
int diffPatterns(const string& src, int len, int setSize) {
int cnt = 0;
node* table[1 << 15];
int tableSize = 1 << 15;
for (int i = 0; i < tableSize; ++i) {
table[i] = NULL;
}
unsigned int hashValue = 0;
int end = (int)src.size() - len;
for (int i = 0; i <= end; ++i) {
hashValue = hashF(src, i, len);
if (table[hashValue] == NULL) {
table[hashValue] = new node(i);
cnt ++;
} else {
if (!compList(src, i, table[hashValue], len)) {
cnt ++;
};
}
}
for (int i = 0; i < tableSize; ++i) {
deleteList(table[i]);
}
return cnt;
}
【问题讨论】:
-
你真的需要找到所有的子字符串还是只需要它们的数量?
-
你的代码有什么问题?你只想让它更快?
-
@NathanOliver 只是数字
-
@tobi303 更快
-
如果这段代码大部分时间都在用
2^15元素数组填充NULLs,我不会感到惊讶。只需使用unordered_set<string>或类似名称。