题目:
Given two strings s and t, determine if they are isomorphic.
Two strings s and t 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.
给定两个字串,判断一字串中的字元是否可透过字元替换而变成另一个字串
要特别注意的是,替换的关係仅能是一对一映射的
ex:(1)input:"egg","add"=>output: true(e换a,g换d)
(2)input:"foo","bar"=>output: false(f换b,o换a,o换r,很明显o的替换关係不是1对1映射)
我们透过建立hash map,纪录对应关係,观察是否有非一对一关係
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: d={} for i in range(len(s)): if s[i] not in d: if t[i] not in d.values(): d[s[i]]=t[i] else: return False else: if d[s[i]]!=t[i]: return False return True
s,t个别表两字串,然后我们设dictionary为d存放对应关係
从头开始存放关係(s[i]是key,t[i]是value),会出现以下几种可能
(1)s[i]不存在key中且t[i]不存在value中:发现新对应关係,纪录
(2)s[i]不存在key中但t[i]存在value中:发现非一对一关係,return False
(3)s[i]存在key中且对应值和t[i]相同:发现重複的关係而已,无视
(4)s[i]存在key中但对应值和t[i]不同:发现非一对一关係,return False
若纪录完都没发现非一对一关係就return True
最后执行时间30ms(faster than 99.74%)
那我们下题见