字符串哈希(String Hashing)是一种将字符串映射成整数值的技术。它在解决字符串相关问题中非常有用,例如在计算不同字符串的数量、字符串匹配、模式匹配等问题中广泛应用。下面详细讲解字符串哈希的原理和用途: 原理:
hash_value = (hash_value * base + char_value) % modulo
hash_value
是当前字符串的哈希值,初始化为 0。base
是所选的基数。char_value
是当前字符的整数值(例如,字符 'a' 对应的整数值)。modulo
是一个用来防止哈希值溢出的模数,通常选取一个较大的质数。hash_value
即为字符串的哈希值。
用途:
字符串哈希的主要用途包括:go#include <iostream>
#include <vector>
// 自定义哈希函数,用于计算字符串的哈希值
int customHash(const std::string& str) {
int prime = 31; // 选择一个较大的质数
int hashValue = 0;
for (char c : str) {
hashValue = (hashValue * prime + c) % 1000000007; // 防止哈希值溢出
}
return hashValue;
}
int main() {
int N;
std::cin >> N; // 读取字符串的个数
std::vector<std::string> strings; // 用于存储输入的字符串
std::vector<int> hashValues; // 用于存储字符串的哈希值
int uniqueCount = 0; // 用于记录不同字符串的数量
for (int i = 0; i < N; ++i) {
std::string str;
std::cin >> str; // 读取每个字符串
int hashValue = customHash(str); // 计算字符串的哈希值
bool isUnique = true;
for (int j = 0; j < i; ++j) {
// 检查是否已存在相同哈希值的字符串
if (hashValues[j] == hashValue) {
isUnique = false;
break;
}
}
if (isUnique) {
strings.push_back(str); // 如果是新字符串,存储它
hashValues.push_back(hashValue); // 存储哈希值
uniqueCount++; // 唯一字符串数量加一
}
}
std::cout << uniqueCount << std::endl; // 输出不同字符串的数量
return 0;
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!