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

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

因此我们可以用哈希和相等来判断顺序颠倒或顺序混乱的字符串是否相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值