|
| 1 | +/** |
| 2 | + * 1657. Determine if Two Strings Are Close |
| 3 | + * https://leetcode.com/problems/determine-if-two-strings-are-close/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Two strings are considered close if you can attain one from the other using the following |
| 7 | + * operations: |
| 8 | + * |
| 9 | + * - Operation 1: Swap any two existing characters. |
| 10 | + * For example, abcde -> aecdb |
| 11 | + * - Operation 2: Transform every occurrence of one existing character into another existing |
| 12 | + * character, and do the same with the other character. |
| 13 | + * For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) |
| 14 | + * |
| 15 | + * You can use the operations on either string as many times as necessary. |
| 16 | + * |
| 17 | + * Given two strings, word1 and word2, return true if word1 and word2 are close, and false |
| 18 | + * otherwise. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string} word1 |
| 23 | + * @param {string} word2 |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +var closeStrings = function(word1, word2) { |
| 27 | + const map1 = helper(word1); |
| 28 | + const map2 = helper(word2); |
| 29 | + |
| 30 | + for (let i = 0; i < map1.length; i++) { |
| 31 | + if ((map1[i] === 0 || map2[i] === 0) && map1[i] !== map2[i]) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + [map1, map2].forEach(m => m.sort((a, b) => b - a)); |
| 37 | + |
| 38 | + return map1.join('') === map2.join(''); |
| 39 | +}; |
| 40 | + |
| 41 | +function helper(input) { |
| 42 | + const map = Array(26).fill(0); |
| 43 | + for (let i = 0; i < input.length; i++) { |
| 44 | + map[input.charCodeAt(i) - 'a'.charCodeAt(0)]++; |
| 45 | + } |
| 46 | + return map; |
| 47 | +} |
0 commit comments