Skip to content

Commit 93ab11c

Browse files
committed
Create isomorphic-strings.py
1 parent 4822a69 commit 93ab11c

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Python/isomorphic-strings.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
#
4+
# Given two strings s and t, determine if they are isomorphic.
5+
#
6+
# Two strings are isomorphic if the characters in s can be replaced to get t.
7+
#
8+
# All occurrences of a character must be replaced with another character
9+
# while preserving the order of characters. No two characters may map to
10+
# the same character but a character may map to itself.
11+
#
12+
# For example,
13+
# Given "egg", "add", return true.
14+
#
15+
# Given "foo", "bar", return false.
16+
#
17+
# Given "paper", "title", return true.
18+
#
19+
# Note:
20+
# You may assume both s and t have the same length.
21+
#
22+
23+
class Solution:
24+
# @param {string} s
25+
# @param {string} t
26+
# @return {boolean}
27+
def isIsomorphic(self, s, t):
28+
if len(s) != len(t):
29+
return False
30+
31+
return self.halfIsom(s, t) and self.halfIsom(t, s)
32+
33+
def halfIsom(self, s, t):
34+
res = {}
35+
for i in xrange(len(s)):
36+
if s[i] not in res:
37+
res[s[i]] = t[i]
38+
elif res[s[i]] != t[i]:
39+
return False
40+
return True

0 commit comments

Comments
 (0)