哈希求和方式判斷相似字符串

哈希算法(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是相等的,但是兩個字符串的順序是不同的。

因此我們可以用哈希和相等來判斷順序顛倒或順序混亂的字符串是否相同。

發佈了26 篇原創文章 · 獲贊 26 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章