All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0801_0900.s0854_k_similar_strings.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0801_0900.s0854_k_similar_strings;

// #Hard #String #Breadth_First_Search #2022_03_27_Time_2_ms_(99.58%)_Space_42.6_MB_(97.17%)

/**
 * 854 - K-Similar Strings\.
 *
 * Hard
 *
 * Strings `s1` and `s2` are `k` **\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`.
 *
 * Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k` **\-similar**.
 *
 * **Example 1:**
 *
 * **Input:** s1 = "ab", s2 = "ba"
 *
 * **Output:** 1
 *
 * **Example 2:**
 *
 * **Input:** s1 = "abc", s2 = "bca"
 *
 * **Output:** 2
 *
 * **Constraints:**
 *
 * *   `1 <= s1.length <= 20`
 * *   `s2.length == s1.length`
 * *   `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`.
 * *   `s2` is an anagram of `s1`.
**/
public class Solution {
    public int kSimilarity(String a, String b) {
        int ans = 0;
        char[] achars = a.toCharArray();
        char[] bchars = b.toCharArray();
        ans += getAllPerfectMatches(achars, bchars);
        for (int i = 0; i < achars.length; i++) {
            if (achars[i] == bchars[i]) {
                continue;
            }
            return ans + checkAllOptions(achars, bchars, i, b);
        }
        return ans;
    }

    private int checkAllOptions(char[] achars, char[] bchars, int i, String b) {
        int ans = Integer.MAX_VALUE;
        for (int j = i + 1; j < achars.length; j++) {
            if (achars[j] == bchars[i] && achars[j] != bchars[j]) {
                swap(achars, i, j);
                ans = Math.min(ans, 1 + kSimilarity(new String(achars), b));
                swap(achars, i, j);
            }
        }
        return ans;
    }

    private int getAllPerfectMatches(char[] achars, char[] bchars) {
        int ans = 0;
        for (int i = 0; i < achars.length; i++) {
            if (achars[i] == bchars[i]) {
                continue;
            }
            for (int j = i + 1; j < achars.length; j++) {
                if (achars[j] == bchars[i] && bchars[j] == achars[i]) {
                    swap(achars, i, j);
                    ans++;
                    break;
                }
            }
        }
        return ans;
    }

    private void swap(char[] a, int i, int j) {
        char temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy