Skip to content

Commit 9f45e59

Browse files
committed
Determine if Two Strings Are Close
1 parent d4d3f50 commit 9f45e59

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/determine-if-two-strings-are-close/
3+
4+
Two strings are considered close if you can attain one from the other using the following operations:
5+
Operation 1: Swap any two existing characters.
6+
For example, abcde -> aecdb
7+
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the
8+
other character.
9+
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
10+
You can use the operations on either string as many times as necessary.
11+
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
12+
13+
Example 1:
14+
Input: word1 = "abc", word2 = "bca"
15+
Output: true
16+
Explanation: You can attain word2 from word1 in 2 operations.
17+
Apply Operation 1: "abc" -> "acb"
18+
Apply Operation 1: "acb" -> "bca"
19+
20+
Example 2:
21+
Input: word1 = "a", word2 = "aa"
22+
Output: false
23+
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
24+
25+
Example 3:
26+
Input: word1 = "cabbba", word2 = "abbccc"
27+
Output: true
28+
Explanation: You can attain word2 from word1 in 3 operations.
29+
Apply Operation 1: "cabbba" -> "caabbb"
30+
Apply Operation 2: "caabbb" -> "baaccc"
31+
Apply Operation 2: "baaccc" -> "abbccc"
32+
33+
Example 4:
34+
Input: word1 = "cabbba", word2 = "aabbss"
35+
Output: false
36+
Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.
37+
38+
Constraints:
39+
1 <= word1.length, word2.length <= 105
40+
word1 and word2 contain only lowercase English letters.
41+
"""
42+
class Solution:
43+
def closeStrings(self, word1: str, word2: str) -> bool:
44+
letters1 = [0] * 26
45+
letters2 = [0] * 26
46+
for word in word1:
47+
letters1[ord(word) - ord('a')] += 1
48+
49+
for word in word2:
50+
letters2[ord(word) - ord('a')] += 1
51+
52+
53+
count = {}
54+
for i in range(len(letters1)):
55+
if letters1[i]:
56+
if letters1[i] in count and letters1[count[letters1[i]]]:
57+
count.pop(letters1[i])
58+
else:
59+
count[letters1[i]] = i
60+
if letters2[i]:
61+
if letters2[i] in count and letters2[count[letters2[i]]]:
62+
count.pop(letters2[i])
63+
else:
64+
count[letters2[i]] = i
65+
66+
return False if count else True

0 commit comments

Comments
 (0)