File tree 1 file changed +68
-0
lines changed
scripts/algorithms/K/KSimilar Strings
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 216 ms (Top 26.27%) | Memory: 92 MB (Top 25.57%)
2
+ class Solution {
3
+ public int kSimilarity (String s1 , String s2 ) {
4
+ HashSet <String > vis = new HashSet <>();
5
+
6
+ ArrayDeque <String > queue = new ArrayDeque <>();
7
+ int level = 0 ;
8
+ queue .add (s1 );
9
+
10
+ while (queue .size () > 0 ){
11
+ int size = queue .size ();
12
+ for (int i =0 ;i <size ;i ++){
13
+
14
+ String rem = queue .remove (); // remove
15
+
16
+ if (vis .contains (rem )){ // Mark*
17
+ continue ;
18
+ }
19
+ vis .add (rem );
20
+
21
+ if (rem .equals (s2 )){ // Work
22
+ return level ;
23
+ }
24
+
25
+ // Add
26
+ for (String s : getNeighbors (rem ,s2 )){
27
+ if (!vis .contains (s )){
28
+ queue .add (s );
29
+ }
30
+ }
31
+ }
32
+ level ++;
33
+ }
34
+ return -1 ;
35
+ }
36
+
37
+ public ArrayList <String > getNeighbors (String rem ,String s2 ){
38
+ ArrayList <String > res = new ArrayList <>();
39
+
40
+ int idx = -1 ;
41
+ for (int i =0 ;i <rem .length ();i ++){
42
+ if (rem .charAt (i ) != s2 .charAt (i )){
43
+ idx = i ;
44
+ break ;
45
+ }
46
+ }
47
+
48
+ for (int j =idx +1 ;j <rem .length ();j ++){
49
+ if (rem .charAt (j ) == s2 .charAt (idx )){
50
+ String s = swap (rem ,idx ,j );
51
+ res .add (s );
52
+ }
53
+ }
54
+
55
+ return res ;
56
+ }
57
+
58
+ public String swap (String str ,int i ,int j ){
59
+ StringBuilder sb = new StringBuilder (str );
60
+ char chi = sb .charAt (i );
61
+ char chj = sb .charAt (j );
62
+
63
+ sb .setCharAt (i ,chj );
64
+ sb .setCharAt (j ,chi );
65
+
66
+ return sb .toString ();
67
+ }
68
+ }
You can’t perform that action at this time.
0 commit comments