-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathisomorphic.py
More file actions
72 lines (60 loc) · 2.13 KB
/
isomorphic.py
File metadata and controls
72 lines (60 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# https://leetcode.com/problems/isomorphic-strings/
#
# Given two strings s and t, determine if they are isomorphic.
#
# Two strings are isomorphic if the characters in s can be replaced to get t.
#
# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
#
# For example,
# Given "egg", "add", return true.
#
# Given "foo", "bar", return false.
#
# Given "paper", "title", return true.
import unittest
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
else:
list_s = list(s)
list_t = list(t)
my_dict = {}
for i in xrange(len(s)):
if list_s[i] in my_dict:
if my_dict[list_s[i]] == list_t[i]:
continue
else:
return False
else:
my_dict[list_s[i]] = list_t[i]
if len(set(my_dict.values()))<len(my_dict.keys()):
return False
else:
return True
class TestIsomorphic(unittest.TestCase):
my_solution = Solution()
def test_default_pass(self):
self.assertTrue(self.my_solution.isIsomorphic("add","egg"))
def test_5_character_pass(self):
self.assertTrue(self.my_solution.isIsomorphic("paper","title"))
def test_default_fail(self):
self.assertFalse(self.my_solution.isIsomorphic("foo","bar"))
def test_aa_ab(self):
self.assertFalse(self.my_solution.isIsomorphic("aa","ab"))
# The check in line 39 was written to catch this failure
def test_ab_aa(self):
self.assertFalse(self.my_solution.isIsomorphic("ab","aa"))
if __name__ == "__main__":
unittest.main()
my_solution = Solution()
# print my_solution.isIsomorphic("add","egg")
# print my_solution.isIsomorphic("Hello","World")
# print my_solution.isIsomorphic("paper","title")
print my_solution.isIsomorphic("ab","aa")