Isomorphic Strings
Question
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.
Note: You may assume both s and t have the same length.
Tags
- Array
- Hashmap
Thought
Use two hash map two describe the mapping relation between the characters in these two string.
Code
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
sourceMap, targetMap = dict(), dict()
for i in xrange(len(s)):
source = sourceMap.get(t[i], None)
target = targetMap.get(s[i], None)
if source is None and target is None:
sourceMap[t[i]] = s[i]
targetMap[s[i]] = t[i]
elif source != s[i] or target != t[i]:
return False
return True