205. 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.
Note:
You may assume both s and t have the same length.
解题方案
标签:String
思路:
- 使用两个dict保存映射关系,遍历字符串,如果其中映射关系出现了不一一对应的情况,那么就返回False,如果始终没问题那么返回True
代码:
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
map1 = {}
map2 = {}
for index,item in enumerate(s):
if (item in map1 and map1[item] != t[index]) or\
(t[index] in map2 and map2[t[index]] != item):
return False
else:
map1[item] = t[index]
map2[t[index]] = item
return True