学过之前的并查集后,发现就很简单了,简单的改造一下并查集,并且按照并查集的三步走策略,就做出来了:


class Solution {
private class UnionFind{
Map<String, String> parent = new HashMap<>();
public UnionFind(int n, String[] names){
for(int i=0; i<n; i++){
this.parent.put(names[i], names[i]);
}
}
public void union(String x, String y){
String rootX = find(x);
String rootY = find(y);
if(rootX.equals("") || rootY.equals("")){
return;
}
if(rootX.equals(rootY)){
return;
}
if(rootX.compareTo(rootY) < 0){
parent.put(rootY, rootX);
}else {
parent.put(rootX, rootY);
}
}
public String find(String x){
if(!parent.containsKey(x)){
return "";
}
if(!x.equals(parent.get(x))){
parent.put(x, find(parent.get(x)));
}
return parent.get(x);
}
}
public String[] trulyMostPopular(String[] names, String[] synonyms) {
String newNames[] = new String[names.length];
int rank[] = new int[names.length];
Map<String, Integer> sign = new HashMap<>();
// 第一步
for(int i=0; i<names.length; i++){
newNames[i] = names[i].split("\\(")[0];
String str = names[i].split("\\(")[1];
rank[i] = Integer.valueOf(str.substring(0, str.length()-1));
sign.put(newNames[i], rank[i]);
}
UnionFind unionFind = new UnionFind(newNames.length, newNames);
for(String syn: synonyms){
String name1 = syn.split(",")[0];
String name2 = syn.split(",")[1];
name1 = name1.substring(1, name1.length());
name2 = name2.substring(0, name2.length()-1);
unionFind.union(name1, name2);
}
// 第二步
Map<String, Integer> map = new HashMap<>();
for(String name: newNames){
String root = unionFind.find(name);
if(!map.containsKey(root)){
map.put(root, sign.get(name));
}else {
map.put(root, map.get(root) + sign.get(name));
}
}
// 第三步
String strRes[] = new String[map.size()];
int index = 0;
for(String k: map.keySet()){
strRes[index] = k + "(" + map.get(k) + ")";
index++;
}
return strRes;
}
}
188

被折叠的 条评论
为什么被折叠?



