|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1657. Determine if Two Strings Are Close |
| 4 | +# https://leetcode.com/problems/determine-if-two-strings-are-close |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +Two strings are considered close if you can attain one from the other using the following operations: |
| 9 | +
|
| 10 | +Operation 1: Swap any two existing characters. |
| 11 | +For example, abcde -> aecdb |
| 12 | +Operation 2: Transform every occurrence of one existing character into another existing 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 | +You can use the operations on either string as many times as necessary. |
| 15 | +
|
| 16 | +Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. |
| 17 | +
|
| 18 | +Example 1: |
| 19 | +Input: word1 = "abc", word2 = "bca" |
| 20 | +Output: true |
| 21 | +Explanation: You can attain word2 from word1 in 2 operations. |
| 22 | +Apply Operation 1: "abc" -> "acb" |
| 23 | +Apply Operation 1: "acb" -> "bca" |
| 24 | +
|
| 25 | +Example 2: |
| 26 | +Input: word1 = "a", word2 = "aa" |
| 27 | +Output: false |
| 28 | +Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. |
| 29 | +
|
| 30 | +Example 3: |
| 31 | +Input: word1 = "cabbba", word2 = "abbccc" |
| 32 | +Output: true |
| 33 | +Explanation: You can attain word2 from word1 in 3 operations. |
| 34 | +Apply Operation 1: "cabbba" -> "caabbb" |
| 35 | +Apply Operation 2: "caabbb" -> "baaccc" |
| 36 | +Apply Operation 2: "baaccc" -> "abbccc" |
| 37 | +
|
| 38 | +Constraints: |
| 39 | +1 <= word1.length, word2.length <= 105 |
| 40 | +word1 and word2 contain only lowercase English letters. |
| 41 | +=end |
| 42 | + |
| 43 | +# @param {String} word1 |
| 44 | +# @param {String} word2 |
| 45 | +# @return {Boolean} |
| 46 | +def close_strings(word1, word2) |
| 47 | + word1, word2 = word1.chars, word2.chars |
| 48 | + |
| 49 | + return false unless word1.uniq.sort.eql? word2.uniq.sort |
| 50 | + |
| 51 | + word1.tally.values.sort.eql? word2.tally.values.sort |
| 52 | +end |
| 53 | + |
| 54 | +# **************** # |
| 55 | +# TEST # |
| 56 | +# **************** # |
| 57 | + |
| 58 | +require "test/unit" |
| 59 | + |
| 60 | +class Test_close_strings < Test::Unit::TestCase |
| 61 | + def test_ |
| 62 | + assert_equal true, close_strings("abc", "bca") |
| 63 | + assert_equal false, close_strings("a", "aa") |
| 64 | + assert_equal true, close_strings("cabbba", "abbccc") |
| 65 | + end |
| 66 | +end |
0 commit comments