Finding the minimum number of swaps to convert one string to another, where the strings may have repeated characters

后端 未结 4 1320
栀梦
栀梦 2020-12-02 21:03

I was looking through a programming question, when the following question suddenly seemed related.

How do you convert a string to another string using as few swaps a

4条回答
  •  情歌与酒
    2020-12-02 21:34

    You can construct the "difference" strings S and S', i.e. a string which contains the characters at the differing positions of the two strings, e.g. for acbacb and abcabc it will be cbcb and bcbc. Let us say this contains n characters.

    You can now construct a "permutation graph" G which will have n nodes and an edge from i to j if S[i] == S'[j]. In the case of all unique characters, it is easy to see that the required number of swaps will be (n - number of cycles in G), which can be found out in O(n) time.

    However, in the case where there are any number of duplicate characters, this reduces to the problem of finding out the largest number of cycles in a directed graph, which, I think, is NP-hard, (e.g. check out: http://www.math.ucsd.edu/~jverstra/dcig.pdf ).

    In that paper a few greedy algorithms are pointed out, one of which is particularly simple:

    1. At each step, find the minimum length cycle in the graph (e.g. Find cycle of shortest length in a directed graph with positive weights )
    2. Delete it
    3. Repeat until all vertexes have not been covered.

    However, there may be efficient algorithms utilizing the properties of your case (the only one I can think of is that your graphs will be K-partite, where K is the number of unique characters in S). Good luck!

    Edit: Please refer to David's answer for a fuller and correct explanation of the problem.

提交回复
热议问题