Skip to content

Commit 673c604

Browse files
authored
Create 854.K-Similar-Strings.cpp
1 parent 1779315 commit 673c604

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public:
3+
int kSimilarity(string A, string B)
4+
{
5+
if (A==B) return 0;
6+
7+
queue<string>q;
8+
q.push(A);
9+
10+
int step = -1;
11+
unordered_set<string>visited;
12+
visited.insert(A);
13+
14+
while (!q.empty())
15+
{
16+
int len = q.size();
17+
step++;
18+
19+
while (len--)
20+
{
21+
string str = q.front();
22+
q.pop();
23+
24+
int i = 0;
25+
while (str[i]==B[i])
26+
i++;
27+
28+
for (int j=i+1; j<str.size(); j++)
29+
{
30+
if (str[j]!=B[i])
31+
continue;
32+
33+
string newStr = str;
34+
swap(newStr[i], newStr[j]);
35+
36+
if (newStr==B)
37+
return step+1;
38+
39+
if (visited.find(newStr)==visited.end())
40+
{
41+
q.push(newStr);
42+
visited.insert(newStr);
43+
}
44+
45+
//cout<<str<<": "<<newStr<<endl;
46+
}
47+
}
48+
49+
}
50+
51+
return -1;
52+
53+
}
54+
};

0 commit comments

Comments
 (0)