[LeetCode] K-Similar Strings

854. K-Similar Strings

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
unordered_map<string, int> dp;
public:
int kSimilarity(string A, string B) {
if(dp.count(A)) return dp[A];
int& res = dp[A] = INT_MAX;
for(int i = 0; i < A.length(); i++) {
if(A[i] == B[i]) continue;
vector<int> match;
for(int j = i + 1; j < A.length(); j++) {
if(B[i] != A[j]) continue;
match.push_back(j);
if(B[j] == A[i]) {
swap(A[i], A[j]);
return res = 1 + kSimilarity(A.substr(i + 1), B.substr(i + 1));
}
}

for(auto& j : match) {
swap(A[i], A[j]);
res = min(res, 1 + kSimilarity(A.substr(i + 1), B.substr(i + 1)));
swap(A[i], A[j]);
}

return res;
}
return res = 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/k-similar-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.