Leetcode in Java && Oracle
424 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
image_2023-01-15_02-26-20.png
65.8 KB
Runtime2 msBeats88.7%
Memory40.4 MBBeats99.43%

#N1061. Lexicographically Smallest Equivalent String
problem link
#solution
class Solution {
public String smallestEquivalentString(String s1, String s2, String base) {
int[] graph = new int[26];
for(int i=0; i<26; i++) graph[i]=i;
for(int i=0; i<s1.length(); i++){
int a1=s1.charAt(i)-'a';
int a2=s2.charAt(i)-'a';
int p1=find(graph, a1);
int p2=find(graph, a2);
if(p1<p2) graph[p2]=p1;
else graph[p1]=p2;
}
StringBuilder sb = new StringBuilder();
for(Character ch: base.toCharArray())
sb.append((char)(find(graph, ch-'a')+'a'));
return sb.toString();
}
public int find(int[] graph, int x){
while(x!=graph[x])
x=graph[x];
return x;
}
}
👍51