forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k-similar-strings.cpp
39 lines (37 loc) · 1.18 KB
/
k-similar-strings.cpp
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
30
31
32
33
34
35
36
37
38
39
// Time: O(n * n!/(c_a!*...*c_z!), n is the length of A, B,
// c_a...c_z is the count of each alphabet,
// n = sum(c_a...c_z)
// Space: O(n * n!/(c_a!*...*c_z!)
class Solution {
public:
int kSimilarity(string A, string B) {
queue<string> q;
unordered_set<string> lookup;
lookup.emplace(A);
q.emplace(A);
int result = 0;
while (!q.empty()) {
for (int size = q.size() - 1; size >= 0; --size) {
auto s = q.front(); q.pop();
if (s == B) {
return result;
}
int i;
for (i = 0; s[i] == B[i]; ++i);
for (int j = i + 1; j < s.length(); ++j){
if (s[j] == B[j] || s[i] != B[j]) {
continue;
}
swap(s[i], s[j]);
if (!lookup.count(s)) {
lookup.emplace(s);
q.emplace(s);
}
swap(s[i], s[j]);
}
}
++result;
}
return result;
}
};