Skip to content

Commit

Permalink
Create 854.K-Similar-Strings.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Oct 18, 2019
1 parent 1779315 commit 673c604
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions BFS/854.K-Similar-Strings/854.K-Similar-Strings.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class Solution {
public:
int kSimilarity(string A, string B)
{
if (A==B) return 0;

queue<string>q;
q.push(A);

int step = -1;
unordered_set<string>visited;
visited.insert(A);

while (!q.empty())
{
int len = q.size();
step++;

while (len--)
{
string str = q.front();
q.pop();

int i = 0;
while (str[i]==B[i])
i++;

for (int j=i+1; j<str.size(); j++)
{
if (str[j]!=B[i])
continue;

string newStr = str;
swap(newStr[i], newStr[j]);

if (newStr==B)
return step+1;

if (visited.find(newStr)==visited.end())
{
q.push(newStr);
visited.insert(newStr);
}

//cout<<str<<": "<<newStr<<endl;
}
}

}

return -1;

}
};

0 comments on commit 673c604

Please sign in to comment.