854 K-Similar Strings

1. Question

Strings AandBareK-similar (for some non-negative integerK) if we can swap the positions of two letters inAexactlyK times so that the resulting string equalsB.

Given two anagramsAandB, return the smallestK for whichAandBareK-similar.

Example 1:

Input: A = "ab", B = "ba"
Output: 1

Example 2:

Input: A = "abc", B = "bca"
Output: 2

Example 3:

Input: A = "abac", B = "baca"
Output: 2

Example 4:

Input: A = "aabc", B = "abca"
Output: 2

Note:

  1. 1 <= A.length == B.length <= 20

  2. AandBcontain only lowercase letters from the set{'a', 'b', 'c', 'd', 'e', 'f'}

2. Implementation

(1) BFS

3. Time & Space Complexity

BFS: 时间复杂度O(n^2), 空间复杂度O(n)

Last updated

Was this helpful?