๐ ๋ฌธ์
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.
๐ซ ์์
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"
๐ ๋ฌธ์ ํ์ด
์ด ๋ฌธ์ ์์ ์ฐ๋ฆฌ๊ฐ ํ ์ ์๋ ์ต์ ์ ์ฃผ์ด์ง ๋ฌธ์์ด ์ค ๋ ๊ฐ์ ์์น๋ฅผ ์ค์ํ๋ ๊ฒ๊ณผ ์ฃผ์ด์ง ๋ฌธ์์ด ์ค ๋ ์ข ๋ฅ์ ๋ฌธ์๋ฅผ ๊ณจ๋ผ ๊ทธ ์ข ๋ฅ ์ ์ฒด๋ฅผ ์ค์ํ๋ ๊ฒ์ด๋ค.
์ ๋ฆฌํด๋ณด์๋ฉด ์ฃผ์ด์ง ๋ฌธ์์ด์์ ์์ ํ ์๋ก์ด ์ํ๋ฒณ์ ์ถ๊ฐํ ์๋ ์๊ณ , ์ํ๋ฒณ์ด ๋ฑ์ฅํ๋ ์๋ค์ ๊ฐ๋ค์ ๋ณํ์ง ์๋๋ค.
aabbb์์ ์คํผ๋ ์ด์ 2๋ฅผ ์ ์ฉํ๋ฉด bbaaa๊ฐ ๋๋ค.
์์ ์ ํ๊ธฐ ์ ์๋ a๊ฐ 2๊ฐ, b๊ฐ 3๊ฐ ์์๊ณ , ์์ ์ ์ฉ ํ์๋ a๊ฐ 3๊ฐ, b๊ฐ 2๊ฐ๊ฐ ๋์๋ค. 2์ 3์ ๊ฐ์ ๋ณํ์ง ์์๊ณ , ๋ฌธ์์ด์ ํฌํจ๋์ด ์๋ ์ํ๋ฒณ a์b๋ ์ฌ์ ํ ์กด์ฌํ๊ณ ์๋ค.
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์๋ word1๊ณผ word2์ ์กด์ฌํ๋ ์ํ๋ฒณ์ด ๊ฐ์์ง, ๊ทธ๋ฆฌ๊ณ ๋ฑ์ฅํ๋ ์ํ๋ฒณ ๊ฐฏ์๊ฐ ์๋ก ๋์ผํ์ง๋ฅผ ํ์ ํ๋ฉด ๋๋ค.
ํ์ด์ฌ์์๋ Counter๋ฅผ ์ฌ์ฉํ๋ฉด ๋ฐ๋ก ๋ฌธ์์ด์์ ๋ฌธ์๊ฐ ๋ช ๋ฒ ๋ฑ์ฅํ์๋์ง ์ธ์ค๋ค. (dict ํ)
์ฝ๋ํฌ์ค์์ ๋ณผ๋ฒํ ๋ฌธ์ ์๋ค.
๐ป ์ฝ๋
python
1 2 3 4 5 | class Solution: def closeStrings(self, word1: str, word2: str) -> bool: cnt1 = Counter(word1) cnt2 = Counter(word2) return cnt1.keys() == cnt2.keys() and sorted(cnt1.values()) == sorted(cnt2.values()) | cs |
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public boolean closeStrings(String word1, String word2) { Map<Character, Integer> cnt1 = generateCnt(word1); Map<Character, Integer> cnt2 = generateCnt(word2); List<Integer> val1 = new ArrayList<>(cnt1.values()); List<Integer> val2 = new ArrayList<>(cnt2.values()); Collections.sort(val1); Collections.sort(val2); return Objects.equals(cnt1.keySet(), cnt2.keySet()) && Objects.equals(val1, val2); } public Map<Character, Integer> generateCnt(String word) { Map<Character, Integer> res = new HashMap<>(); for (int i = 0; i < word.length(); i++) { int val = res.getOrDefault(word.charAt(i), 0); res.put(word.charAt(i), val + 1); } return res; } } | cs |
๐ ๋ฌธ์ ๋งํฌ
'Problem Solving > ๋ฆฌํธ์ฝ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 2563. Count the Number of Fair Pairs (0) | 2024.11.13 |
---|---|
[LeetCode] 406. Queue Reconstruction by Height (2) | 2024.11.08 |
[LeetCode] 3036. Number of Subarrays That Match a Pattern II (0) | 2024.02.11 |
[LeetCode] 380. Insert Delete GetRandom O(1) (1) | 2024.01.21 |