.Zzumbong

[leetCode/JS] 1657. Determine if Two Strings Are Close 본문

coding test/leetCode

[leetCode/JS] 1657. Determine if Two Strings Are Close

쭘봉 2022. 12. 2. 11:26

난이도 [ 🤔 ] Medium

문제 설명

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

 

문자를 이동하고 바꾸고 문제가 겁나 복잡한데, 예제를 살펴보면 조건들이 있어서 조금 덜 복잡하다.
1. 등장한 문자의 종류가 같아야한다.
  cabbba// abbccc는 각각 a,b,c 만 등장하기 때문에 true이다.
  만약 aabbcc // aabbcs 라면, abc // abcs 로 false이다.
2. 문자의 등장한 숫자가 서로 같아야 한다.
   cabbba // abbccc는 각각 {a: 2, b: 3, c:1} // {a:1, b:2, c:3} 으로 231 // 123으로 서로 1, 2, 3을 가지고 있다. true.
   만약 abbzzca // babzzcz는 {a:2, b:2, c:1, z:1} // {a:1, b:2, c:1, z:3} // 2211, 1213 으로 false가 된다.

 

입출력 예

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

 

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

 

Example 3

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

 

Constraints

  • 1 <= word1.length, word2.length <= 105
  • word1 and word2 contain only lowercase English letters.

 


 

 

내 솔루션

  • 각 word 마다 hashmap 컨셉으로 문자종류, 문자마다 등장횟수를 sort, join 해서 비교한다.
/**
 * @param {string} word1
 * @param {string} word2
 * @return {boolean}
 */
var closeStrings = function(word1, word2) {
  // word1 = "cabbba" word2 = "abbccc"
  if(word1.length !== word2.length) return false;

  const get = (word) => {
    const map = {};
    for(let i = 0; i < word.length; i++) {
      if(!map[word[i]]) map[word[i]] = 1;
      else map[word[i]]++;
    }
    return [Object.keys(map).sort((a,b)=>a>b?-1:1).join(''), Object.values(map).sort((a,b)=>a-b).join('')];
  }
  const a = get(word1); // [ 'abc', '123' ]
  const b = get(word2); // [ 'abc', '123' ]
  return a[0] === b[0] && a[1] === b[1];
};

 

 

감상평

  • 내부함수도 만들고 for, sort, join을 여러 번해서 생각보다 느릴줄 알았는데, 적당한듯?

Comments