|
| 1 | +/** |
| 2 | + * 1061. Lexicographically Smallest Equivalent String |
| 3 | + * https://leetcode.com/problems/lexicographically-smallest-equivalent-string/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two strings of the same length s1 and s2 and a string baseStr. |
| 7 | + * |
| 8 | + * We say s1[i] and s2[i] are equivalent characters. |
| 9 | + * - For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'. |
| 10 | + * |
| 11 | + * Equivalent characters follow the usual rules of any equivalence relation: |
| 12 | + * - Reflexivity: 'a' == 'a'. |
| 13 | + * - Symmetry: 'a' == 'b' implies 'b' == 'a'. |
| 14 | + * - Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'. |
| 15 | + * |
| 16 | + * For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" |
| 17 | + * are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent |
| 18 | + * string of baseStr. |
| 19 | + * |
| 20 | + * Return the lexicographically smallest equivalent string of baseStr by using the equivalency |
| 21 | + * information from s1 and s2. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} s1 |
| 26 | + * @param {string} s2 |
| 27 | + * @param {string} baseStr |
| 28 | + * @return {string} |
| 29 | + */ |
| 30 | +var smallestEquivalentString = function(s1, s2, baseStr) { |
| 31 | + const parent = Array(26).fill().map((_, i) => i); |
| 32 | + |
| 33 | + for (let i = 0; i < s1.length; i++) { |
| 34 | + union(s1.charCodeAt(i) - 97, s2.charCodeAt(i) - 97); |
| 35 | + } |
| 36 | + |
| 37 | + return baseStr.split('') |
| 38 | + .map(char => String.fromCharCode(97 + find(char.charCodeAt(0) - 97))) |
| 39 | + .join(''); |
| 40 | + |
| 41 | + function find(x) { |
| 42 | + if (parent[x] !== x) { |
| 43 | + parent[x] = find(parent[x]); |
| 44 | + } |
| 45 | + return parent[x]; |
| 46 | + } |
| 47 | + |
| 48 | + function union(x, y) { |
| 49 | + const rootX = find(x); |
| 50 | + const rootY = find(y); |
| 51 | + if (rootX < rootY) { |
| 52 | + parent[rootY] = rootX; |
| 53 | + } else if (rootX > rootY) { |
| 54 | + parent[rootX] = rootY; |
| 55 | + } |
| 56 | + } |
| 57 | +}; |
0 commit comments