File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ def is_isomorphic (s : str , t : str ) -> bool :
2+ """
3+ LeetCode No. 205 Isomorphic Strings
4+ Given two strings s and t, determine if they are isomorphic.
5+ https://leetcode.com/problems/isomorphic-strings/description/
6+
7+ Two strings s and t are isomorphic if the characters in s can be
8+ replaced to get t.
9+
10+ All occurrences of a character must be replaced with another character
11+ while preserving the order of characters. No two characters may map to
12+ the same character, but a character may map to itself.
13+
14+
15+ >>> is_isomorphic("egg", "add")
16+ True
17+ >>> is_isomorphic("foo", "bar")
18+ False
19+ >>> is_isomorphic("paper", "title")
20+ True
21+ >>> is_isomorphic("ab", "aa")
22+ False
23+ """
24+ if len (s ) != len (t ):
25+ return False
26+
27+ mapping : dict [str , str ] = {}
28+ mapped = set ()
29+
30+ for char_s , char_t in zip (s , t ):
31+ if char_s in mapping :
32+ if mapping [char_s ] != char_t :
33+ return False
34+ else :
35+ if char_t in mapped :
36+ return False
37+ mapping [char_s ] = char_t
38+ mapped .add (char_t )
39+
40+ return True
41+
42+
43+ if __name__ == "__main__" :
44+ import doctest
45+
46+ doctest .testmod ()
47+
48+ print (is_isomorphic ("egg" , "add" )) # True
You can’t perform that action at this time.
0 commit comments