-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path1061. Lexicographically Smallest Equivalent String.java
More file actions
43 lines (35 loc) · 1.27 KB
/
Copy path1061. Lexicographically Smallest Equivalent String.java
File metadata and controls
43 lines (35 loc) · 1.27 KB
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
import java.util.*;
//donot edit this code
class Solution {
public String smallestEquivalentString(String s1, String s2, String baseStr) {
Map<Character, List<Character>> adj = new HashMap<>();
int n = s1.length();
// Build the adjacency list
for (int i = 0; i < n; i++) {
char u = s1.charAt(i);
char v = s2.charAt(i);
adj.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
adj.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
}
StringBuilder result = new StringBuilder();
for (char ch : baseStr.toCharArray()) {
boolean[] visited = new boolean[26];
char minChar = dfs(adj, ch, visited);
result.append(minChar);
}
return result.toString();
}
private char dfs(Map<Character, List<Character>> adj, char ch, boolean[] visited) {
visited[ch - 'a'] = true;
char minChar = ch;
for (char neighbor : adj.getOrDefault(ch, new ArrayList<>())) {
if (!visited[neighbor - 'a']) {
char candidate = dfs(adj, neighbor, visited);
if (candidate < minChar) {
minChar = candidate;
}
}
}
return minChar;
}
}