1+ def can_transform (str1 : str , str2 : str ) -> bool :
2+ """
3+ Check if str1 can transform into str2 by replacing each character in str1
4+ with another character (or the same character).
5+
6+ Args:
7+ str1 (str): The source string.
8+ str2 (str): The target string.
9+
10+ Returns:
11+ bool: True if str1 can be transformed into str2, False otherwise.
12+
13+ Examples:
14+ Input: str1 = "aabcc", str2 = "ccdee"
15+ Output: True
16+ Explanation: 'a'->'c', 'b'->'d', 'c'->'e'
17+
18+ Input: str1 = "leetcode", str2 = "codeleet"
19+ Output: False
20+ Explanation: There's no way to map 'l' and 'e' to satisfy both positions.
21+ """
22+ if len (str1 ) != len (str2 ):
23+ return False
24+
25+ if str1 == str2 :
26+ return True
27+
28+ char_map = {}
29+ for c1 , c2 in zip (str1 , str2 ):
30+ if c1 in char_map :
31+ if char_map [c1 ] != c2 :
32+ return False
33+ else :
34+ char_map [c1 ] = c2
35+
36+ if len (set (str2 )) == 26 :
37+ return str1 == str2
38+
39+ return True
40+
41+
42+ if __name__ == "__main__" :
43+ example1_str1 = "aabcc"
44+ example1_str2 = "ccdee"
45+ result1 = can_transform (example1_str1 , example1_str2 )
46+ print (f"Input: str1 = '{ example1_str1 } ', str2 = '{ example1_str2 } '" )
47+ print (f"Output: { result1 } " )
48+
49+ example2_str1 = "leetcode"
50+ example2_str2 = "codeleet"
51+ result2 = can_transform (example2_str1 , example2_str2 )
52+ print (f"\n Input: str1 = '{ example2_str1 } ', str2 = '{ example2_str2 } '" )
53+ print (f"Output: { result2 } " )
0 commit comments