Isomorphic String
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.
这里的对应关系说的是s[i]对应t[i],而t[i]不一定需要对应s[i]但是这个对应关系必须是唯一不改变的,所以这里最简单清晰的逻辑就是先从s->t的关系利用哈希表扫描检查一遍,再用t->s的关系用另外一个哈希表扫描检查一遍,如果符合逻辑就输出True,当然这里也可以简化到一遍扫描,但是个人觉得逻辑不如两遍这么清晰直接,下面是代码
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
n = len(s)
leftChecker = {}
for i in xrange(n):
if s[i] not in leftChecker:
leftChecker[s[i]] = t[i]
elif leftChecker[s[i]] != t[i]:
return False
rightChecker = {}
for i in xrange(n):
if t[i] not in rightChecker:
rightChecker[t[i]] = s[i]
elif rightChecker[t[i]] != s[i]:
return False
return True