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

后端 未结 4 1329
栀梦
栀梦 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条回答
  •  猫巷女王i
    2020-12-02 21:40

    Hash Map data structure (that allows duplicates) is suitable for solving the problem.

    Let the string be s1 and s2. The algorithm iterates through both the string and whenever a mismatch is found the algorithm maps the character of s1 to s2 i.e char of s1 as key and char of s2 as value is inserted in Hash Map wherever mismatch is occurred.

    After this initialize the result as zero.

    The next step is while the Hash Map is not empty do following:

    1. For any key k find its value v.
    2. Now use value v as the key to lookup in the Hash Map to find value if the found value is equal to k then increment the result by 1 and remove both the keys k and v from the Hash Map.
    3. If the found value is not equal to k then only remove key k from the Hash Map and increment the result.

    result holds your desired output.

提交回复
热议问题