代码拉取完成,页面将自动刷新
// 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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。