-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution854.cs
70 lines (60 loc) · 1.6 KB
/
Solution854.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution853
{
/// <summary>
/// 854. K-Similar Strings - Hard
/// <a href="https://leetcode.com/problems/k-similar-strings">See the problem</a>
/// </summary>
public int KSimilarity(string s1, string s2)
{
if (s1 == s2)
{
return 0;
}
var visited = new HashSet<string>();
var queue = new Queue<string>();
queue.Enqueue(s1);
visited.Add(s1);
var k = 0;
while (queue.Count > 0)
{
var size = queue.Count;
for (int i = 0; i < size; i++)
{
var current = queue.Dequeue();
if (current == s2)
{
return k;
}
var j = 0;
while (current[j] == s2[j])
{
j++;
}
for (int l = j + 1; l < s1.Length; l++)
{
if (current[l] == s2[l] || current[l] != s2[j])
{
continue;
}
var next = Swap(current, j, l);
if (visited.Add(next))
{
queue.Enqueue(next);
}
}
}
k++;
}
return -1;
}
private string Swap(string s, int i, int j)
{
var sb = new StringBuilder(s);
sb[i] = s[j];
sb[j] = s[i];
return sb.ToString();
}
}