哈希算法(c++)
long hashString(string str) {
char *charP = str.data();
long hashCode = 0;
for (; *charP; ++charP) {
hashCode = 5 * hashCode + *charP;
hashCode %= 2353639;
}
return hashCode;
}
哈希算法(scala)可类比到java
def HashString(str: String): Long = {
var hashCode: Long = 0
val bytes = str.getBytes()
for (index <- 0 until bytes.size) {
hashCode = 5 * hashCode + bytes.apply(index)
hashCode %= 2353639
}
hashCode
}
哈希和
思路
我们可以利用上述基础哈希函数来求算每个子串的哈希值,最后加和,比对和与和之间的关系即可判断详细
举例
long hashCode1 = hashString("我");
long hashCode2 = hashString("与");
long hashCode3 = hashString("中国");
//我与中国
long hashAddResult = hashCode1 + hashCode2 + hashCode3;
//中国与我
long hashAddMixResult = hashCode3 + hashCode2 + hashCode1;
上面分别是两个字符串:我与中国,中国与我。(拆分为三个子串:我,与,中国)那么显然hashAddResult与hashAddMixResult是相等的,但是两个字符串的顺序是不同的。
因此我们可以用哈希和相等来判断顺序颠倒或顺序混乱的字符串是否相同。