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
| class Solution { public String smallestEquivalentString(String s1, String s2, String baseStr) { Map<Character, Set<Character>> nodeNeighbors = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { char letterOne = s1.charAt(i), letterTwo = s2.charAt(i); nodeNeighbors.computeIfAbsent(letterOne, (key) -> new HashSet<>()).add(letterTwo); nodeNeighbors.computeIfAbsent(letterTwo, (key) -> new HashSet<>()).add(letterOne); } Map<Character, Character> letterMinCharMapping = new HashMap<>(); StringBuilder ans = new StringBuilder(); for (char letter : baseStr.toCharArray()) { if (!nodeNeighbors.containsKey(letter)) { ans.append(letter); continue; } if (!letterMinCharMapping.containsKey(letter)) { StringBuilder nodes = new StringBuilder(); char minChar = getMinChar(letter, nodeNeighbors, nodes, new HashSet<>()); store(letterMinCharMapping, minChar, nodes.toString()); } ans.append(letterMinCharMapping.get(letter)); } return ans.toString(); }
private char getMinChar(char letter, Map<Character, Set<Character>> nodeNeighbors, StringBuilder nodes, Set<Character> visited) { char currMinChar = letter; nodes.append(letter); for (char neighbor : nodeNeighbors.get(letter)) { if (visited.contains(neighbor)) continue; visited.add(neighbor); char minChar = getMinChar(neighbor, nodeNeighbors, nodes, visited); if (minChar < currMinChar) { currMinChar = minChar; } } return currMinChar; }
private void store(Map<Character, Character> letterMinCharMapping, char minChar, String nodes) { for (char node : nodes.toCharArray()) { letterMinCharMapping.put(node, minChar); } } }
|