📌  相关文章
📜  两根字符串之间的汉明距离

📅  最后修改于: 2022-05-13 01:57:06.630000             🧑  作者: Mango

两根字符串之间的汉明距离

给你两个长度相等的字符串,你必须找到这些字符串之间的汉明距离。
其中两个相等长度的字符串之间的汉明距离是对应字符不同的位置数。
例子:

Input : str1[] = "geeksforgeeks", str2[] = "geeksandgeeks"
Output : 3
Explanation : The corresponding character mismatch are highlighted.
"geeksforgeeks" and "geeksandgeeks"

Input : str1[] = "1011101", str2[] = "1001001"
Output : 2
Explanation : The corresponding character mismatch are highlighted.
"1011101" and "1001001"

这个问题可以通过一种简单的方法来解决,我们遍历字符串并计算相应位置的不匹配。这个问题的扩展形式是编辑距离。
算法 :

int hammingDist(char str1[], char str2[])
{
    int i = 0, count = 0;
    while(str1[i]!='\0')
    {
        if (str1[i] != str2[i])
            count++;
        i++;
    }
    return count;
}

下面是两个字符串的实现。

C++
// C++ program to find hamming distance b/w
// two string
#include
using namespace std;
 
// function to calculate Hamming distance
int hammingDist(char *str1, char *str2)
{
    int i = 0, count = 0;
    while (str1[i] != '\0')
    {
        if (str1[i] != str2[i])
            count++;
        i++;
    }
    return count;
}
 
// driver code
int main()
{
    char str1[] = "geekspractice";
    char str2[] = "nerdspractise";
 
    // function call
    cout << hammingDist (str1, str2);
 
    return 0;
}


Java
// Java program to find hamming distance
// b/w two string
class GFG
{
// function to calculate Hamming distance
static int hammingDist(String str1, String str2)
{
    int i = 0, count = 0;
    while (i < str1.length())
    {
        if (str1.charAt(i) != str2.charAt(i))
            count++;
        i++;
    }
    return count;
}
 
// Driver code
public static void main (String[] args)
{
    String str1 = "geekspractice";
    String str2 = "nerdspractise";
 
    // function call
    System.out.println(hammingDist (str1, str2));
}
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to find
# hamming distance b/w two
# string
 
# Function to calculate
# Hamming distance
def hammingDist(str1, str2):
    i = 0
    count = 0
 
    while(i < len(str1)):
        if(str1[i] != str2[i]):
            count += 1
        i += 1
    return count
 
# Driver code 
str1 = "geekspractice"
str2 = "nerdspractise"
 
# function call
print(hammingDist(str1, str2))
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program to find hamming
// distance b/w two string
using System;
 
class GFG {
     
// function to calculate
// Hamming distance
static int hammingDist(String str1,
                       String str2)
{
    int i = 0, count = 0;
    while (i < str1.Length)
    {
        if (str1[i] != str2[i])
            count++;
        i++;
    }
    return count;
}
 
// Driver code
public static void Main ()
{
    String str1 = "geekspractice";
    String str2 = "nerdspractise";
 
    // function call
    Console.Write(hammingDist(str1, str2));
}
}
 
// This code is contributed by nitin mittal


PHP


Javascript


输出:

4