File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
BFS/854.K-Similar-Strings Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments