205. Isomorphic Strings (easy)
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.
Example 1:
Input: s ="egg",
t ="add"
Output: trueExample 2:
Input: s ="foo",
t ="bar"
Output: falseExample 3:
Input: s ="paper",
t ="title"
Output: true
题意:如果s中的字母可以被替代变成,则两者是同构的。所有出现的字符必须替换为另一个字符同时保留字符的顺序。 没有两个字符可以映射到相同的字符,不存在a->b,c->b即映射是1对1,但字符可以映射到自身a-》a。
使用hashmap
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic = {}
n = len(s)
for i,x in enumerate(s):
if x in dic.keys() and dic[x] != t[i]:return False
elif x not in dic.keys() and t[i] in dic.values():return False
else:dic[x] = t[i]
return True