-
-
Save autotune/e6345fab54f6acab0ba95c45ec15f22a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Create a Python3 function to determine if two strings are close | |
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) | |
"cabbba" -> "abbccc" | |
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. | |
You can use the operations on either string as many times as necessary. | |
class Solution: | |
def closeStrings(self, word1: str, word2: str) -> bool: | |
def close_strings(string1, string2): |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def closeStrings(self, word1: str, word2: str) -> bool: | |
def close_strings(string1, string2): | |
if len(string1) != len(string2): | |
return False | |
else: | |
map1 = dict() | |
map2 = dict() | |
for char in string1: | |
if char not in map1: | |
map1[char] = 1 | |
else: | |
map1[char] += 1 | |
for char in string2: | |
if char not in map2: | |
map2[char] = 1 | |
else: | |
map2[char] += 1 | |
if sorted(map1.keys()) == sorted(map2.keys()): | |
return True | |
else: | |
return False | |
# Operation 1: Swap any two existing characters | |
word1_swap = [char for char in word1] | |
for i in range(len(word1_swap)): | |
for j in range(i): | |
temp = word1_swap[i] | |
word1_swap[i] = word1_swap[j] | |
word1_swap[j] = temp | |
if close_strings(''.join(word1_swap), word2): | |
return True | |
# Revert back | |
temp = word1_swap[i] | |
word1_swap[i] = word1_swap[j] | |
word1_swap[j] = temp | |
# Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character | |
for i in range(len(word1)): | |
for j in range(i): | |
word1_transform = [char for char in word1] | |
word1_transform[i] = word1[j] | |
word1_transform[j] = word1[i] | |
if close_strings(''.join(word1_transform), word2): | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment