Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5d5504a

Browse files
committed
O(n) time and O(n) space using hashmap(Counter)
1 parent f56944b commit 5d5504a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Two strings are considered close if you can attain one from the other using the following operations:
3+
4+
Operation 1: Swap any two existing characters.
5+
For example, abcde -> aecdb
6+
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
7+
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
8+
You can use the operations on either string as many times as necessary.
9+
10+
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
11+
12+
13+
14+
Example 1:
15+
16+
Input: word1 = "abc", word2 = "bca"
17+
Output: true
18+
Explanation: You can attain word2 from word1 in 2 operations.
19+
Apply Operation 1: "abc" -> "acb"
20+
Apply Operation 1: "acb" -> "bca"
21+
Example 2:
22+
23+
Input: word1 = "a", word2 = "aa"
24+
Output: false
25+
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
26+
Example 3:
27+
28+
Input: word1 = "cabbba", word2 = "abbccc"
29+
Output: true
30+
Explanation: You can attain word2 from word1 in 3 operations.
31+
Apply Operation 1: "cabbba" -> "caabbb"
32+
Apply Operation 2: "caabbb" -> "baaccc"
33+
Apply Operation 2: "baaccc" -> "abbccc"
34+
35+
36+
Constraints:
37+
38+
1 <= word1.length, word2.length <= 105
39+
word1 and word2 contain only lowercase English letters.
40+
"""
41+
class Solution:
42+
def closeStrings(self, word1: str, word2: str) -> bool:
43+
count_word1 = collections.Counter(word1)
44+
count_word2 = collections.Counter(word2)
45+
counter1 = collections.Counter(count_word1.values())
46+
counter2 = collections.Counter(count_word2.values())
47+
return len(count_word1.keys() - count_word2.keys()) == 0 and len(counter1 - counter2) == 0

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /