Created
September 22, 2019 04:09
-
-
Save jianminchen/098ddbb27ccb4240b60678da8a937252 to your computer and use it in GitHub Desktop.
Leetcode 1202 - smallest string - union find algorithm - weekly contest 155
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace unionFind | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
public string SmallestStringWithSwaps(string s, IList<IList<int>> pairs) | |
{ | |
var length = s.Length; | |
var parent = new int[length]; | |
for (int i = 0; i < length; i++) | |
parent[i] = i; | |
foreach(var pair in pairs) | |
{ | |
var first = pair[0]; | |
var second = pair[1]; | |
if(parent[first] != parent[second]) | |
{ | |
// union two set; | |
union(parent, parent[first], parent[second]); | |
} | |
} | |
} | |
private static void union(int[] parent, int first, int second) | |
{ | |
int iterate = first; | |
var newParent = parent[second]; | |
while (iterate != newParent) | |
{ | |
var tmp = parent[iterate]; | |
parent[iterate] = newParent; | |
iterate = tmp; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment