📌  相关文章
📜  通过交换两个字符来减少汉明距离

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

通过交换两个字符来减少汉明距离

给定两个字符串S 和 T。找到要交换的两个字母在 S 中的位置,使字符串S 和 T 之间的汉明距离尽可能小。
汉明距离相同长度的两个字符串S和T之间的汉明距离,定义为S和T有不同字符的位置个数
例子:

Input : S = "permanent", T = "pergament"
Output: 4 6

Input : S = "double" T = "bundle"
Output : 4 1

解释 1:最初,S 和 T 之间的汉明距离为 2(在 4 和 6 处)。交换位置 4 和 6 的字母后,它变成了“永久”。这里,汉明距离只有 1。这是可能的最小值。
解释2:交换前:“double”“bundle”,距离=4
交换后:“boudle”“bundle”,距离 = 2

方法 :
在给定的字符串中,汉明距离最多可以减少两个,因为只能移动两个字符。
Case-I:如果两个字符串中有两个位置具有相同的两个字母但以不同的顺序出现(如“bundle”和“double”),则可以将距离减少两倍。
案例二:通过“固定”错误位置的字符可以减一(比如在“permanent”和“pergament”中,这里n与m配对错误,还有不匹配的m,我们可以修复)。
Case-III:如果无法减小汉明距离,则打印 -1。
执行:
案例-I:要将距离减少 2,创建一个二维数组 dp[i][j](i is s[] – 'a' and j is t[] – 'a') 并将其分配给字符串S 中 i 的索引。如果找到重复的对,则打印相应的索引。
案例二:为了将距离减一,维护两个数组 A[] 和 B[]

C++
// C++ code to decrease
// hamming distance using swap.
#include 
using namespace std;
 
#define MAX 26
 
// Function to return the
// swapped indexes to get
// minimum hamming distance.
void Swap(string s, string t, int n)
{
    int dp[MAX][MAX];
    memset(dp, -1, sizeof dp);
 
    // Find the initial hamming
    // distance
    int tot = 0;
    for (int i = 0; i < n; i++)
        if (s[i] != t[i])
            tot++;
     
    // Case-I: To decrease distance
    // by two
    for (int i = 0; i < n; i++) {
 
        // ASCII values of present
        // character.
        int a = s[i] - 'a';
        int b = t[i] - 'a';
 
        if (a == b)
            continue;
 
        // If two same letters appear
        // in different positions
        // print their indexes
        if (dp[a][b] != -1) {
            cout << i + 1 << " "
                << dp[a][b] + 1 << endl;
            return;
        }
 
        // Store the index of
        // letters which is
        // in wrong position
        dp[b][a] = i;
    }
 
    // Case:II
    int A[MAX], B[MAX];
    memset(A, -1, sizeof A);
    memset(B, -1, sizeof B);
 
    for (int i = 0; i < n; i++) {
        int a = s[i] - 'a';
        int b = t[i] - 'a';
        if (a == b)
            continue;
 
        // If misplaced letter
        // is found, print its
        // original index and
        // its new index
        if (A[b] != -1) {
            cout << i + 1 << " " <<
                  A[b] + 1 << endl;
            return;
        }
 
        if (B[a] != -1) {
            cout << i + 1 << " " <<
                  B[a] + 1 << endl;
            return;
        }
 
        // Store the index of
        // letters in wrong position
        A[a] = i;
        B[b] = i;
    }
 
    // Case-III
    cout << -1 << endl;
}
 
// Driver code
int main()
{
    string S = "permanent";
    string T = "pergament";
    int n = S.length();
 
    if (S == "" || T == "")
        cout << "Required string is empty.";
    else
        Swap(S, T, n);
 
    return 0;
}


Java
// Java code to decrease
// hamming distance using swap.
import java.util.Arrays;
 
class GFG
{
     
static final int MAX = 26;
 
// Function to return the
// swapped indexes to get
// minimum hamming distance.
static void Swap(String s, String t, int n)
{
    int dp[][] = new int[MAX][MAX];
    for(int i = 0; i < MAX; i++)
    {
        for(int j = 0; j < MAX; j++)
        {
            dp[i][j]=-1;
        }
    }
 
    // Find the initial hamming
    // distance
    int tot = 0;
    for (int i = 0; i < n; i++)
        if (s.charAt(i) != t.charAt(i))
            tot++;
     
    // Case-I: To decrease distance
    // by two
    for (int i = 0; i < n; i++)
    {
 
        // ASCII values of present
        // character.
        int a = s.charAt(i)- 'a';
        int b = t.charAt(i) - 'a';
 
        if (a == b)
            continue;
 
        // If two same letters appear
        // in different positions
        // print their indexes
        if (dp[a][b] != -1)
        {
            System.out.println(i + 1 + " " +
                            (dp[a][b] + 1));
            return;
        }
 
        // Store the index of
        // letters which is
        // in wrong position
        dp[b][a] = i;
    }
 
    // Case:II
    int A[] = new int[MAX], B[] = new int[MAX];
    Arrays.fill(A, -1);
    Arrays.fill(B, -1);
 
    for (int i = 0; i < n; i++)
    {
        int a = s.charAt(i)- 'a';
        int b = t.charAt(i) - 'a';
        if (a == b)
            continue;
 
        // If misplaced letter
        // is found, print its
        // original index and
        // its new index
        if (A[b] != -1)
        {
            System.out.println(i + 1 + " " +
                                (A[b] + 1));
            return;
        }
 
        if (B[a] != -1)
        {
            System.out.println(i + 1 + " " +
                                 (B[a] + 1));
            return;
        }
 
        // Store the index of
        // letters in wrong position
        A[a] = i;
        B[b] = i;
    }
 
    // Case-III
    System.out.println(-1);
}
 
// Driver code
public static void main(String[] args)
{
    String S = "permanent";
    String T = "pergament";
    int n = S.length();
 
    if (S == "" || T == "")
        System.out.println("Required string is empty.");
    else
        Swap(S, T, n);
}
}
 
// This code is contributed by Rajput-Ji


Python 3
# Python 3 code to decrease
# hamming distance using swap.
MAX = 26
 
# Function to return the swapped indexes
# to get minimum hamming distance.
def Swap(s, t, n):
 
    dp = [[-1 for x in range(MAX)]
              for y in range(MAX)]
 
    # Find the initial hamming
    # distance
    tot = 0;
    for i in range(n):
        if (s[i] != t[i]):
            tot += 1
     
    # Case-I: To decrease distance
    # by two
    for i in range(n) :
 
        # ASCII values of present
        # character.
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
 
        if (a == b):
            continue
 
        # If two same letters appear
        # in different positions
        # print their indexes
        if (dp[a][b] != -1) :
            print(i + 1," ", dp[a][b] + 1)
            return
 
        # Store the index of
        # letters which is
        # in wrong position
        dp[b][a] = i
 
    # Case:II
    A = [-1] * MAX
    B = [-1] * MAX
 
    for i in range(n) :
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
        if (a == b):
            continue
 
        # If misplaced letter is found,
        # print its original index and
        # its new index
        if (A[b] != -1) :
            print( i + 1, A[b] + 1)
            return
 
        if (B[a] != -1) :
            print( i + 1, B[a] + 1)
            return
 
        # Store the index of
        # letters in wrong position
        A[a] = i
        B[b] = i
     
    # Case-III
    print( "-1" )
 
# Driver code
if __name__ == "__main__":
    S = "permanent"
    T = "pergament"
    n = len(S)
 
    if (S == "" or T == ""):
        print("Required string is empty.")
    else:
        Swap(S, T, n)
 
# This code is contributed
# by ChitraNayal


C#
// C# code to decrease
// hamming distance using swap.
using System;
 
class GFG
{
     
static readonly int MAX = 26;
 
    // Function to return the
    // swapped indexes to get
    // minimum hamming distance.
    static void Swap(string s, string t, int n)
    {
        int [,]dp = new int[MAX, MAX];
        for(int i = 0; i < MAX; i++)
        {
            for(int j = 0; j < MAX; j++)
            {
                dp[i, j]=-1;
            }
        }
 
        // Find the initial hamming
        // distance
        int tot = 0;
        for (int i = 0; i < n; i++)
            if (s[i] != t[i])
                tot++;
 
        // Case-I: To decrease distance
        // by two
        for (int i = 0; i < n; i++)
        {
 
            // ASCII values of present
            // character.
            int a = s[i] - 'a';
            int b = t[i] - 'a';
 
            if (a == b)
                continue;
 
            // If two same letters appear
            // in different positions
            // print their indexes
            if (dp[a,b] != -1)
            {
                Console.WriteLine(i + 1 + " " +
                                (dp[a, b] + 1));
                return;
            }
 
            // Store the index of
            // letters which is
            // in wrong position
            dp[b,a] = i;
        }
 
        // Case:II
        int []A = new int[MAX]; int []B = new int[MAX];
        for (int i = 0; i < MAX; i++)
        {
            A[i]=-1;
            B[i]=-1;
        }
 
        for (int i = 0; i < n; i++)
        {
            int a = s[i] - 'a';
            int b = t[i] - 'a';
            if (a == b)
                continue;
 
            // If misplaced letter
            // is found, print its
            // original index and
            // its new index
            if (A[b] != -1)
            {
                Console.WriteLine(i + 1 + " " +
                                    (A[b] + 1));
                return;
            }
 
            if (B[a] != -1)
            {
                Console.WriteLine(i + 1 + " " +
                                    (B[a] + 1));
                return;
            }
 
            // Store the index of
            // letters in wrong position
            A[a] = i;
            B[b] = i;
        }
 
        // Case-III
        Console.WriteLine(-1);
    }
 
    // Driver code
    public static int Main()
    {
        string S = "permanent";
        string T = "pergament";
        int n = S.Length;
 
        if (S == "" || T == "")
            Console.WriteLine("Required string is empty.");
        else
            Swap(S, T, n);
 
        return 0;
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

6 4