哈希算法(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是相等的,但是兩個字符串的順序是不同的。
因此我們可以用哈希和相等來判斷順序顛倒或順序混亂的字符串是否相同。