Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
k-similar-strings.cpp 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-06-18 19:33 +08:00 . Update k-similar-strings.cpp
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助