给定两个字符串 s 和 t ,判断它们是否是同构的。
如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。
每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。
function isIsomorphic(s: string, t: string): boolean {
function getPatten(s:string){
const map = new Map()
const s_arr = []
for(let i=0;i<s.length ;i++){
const char = s[i]
if(!map.has(char)){
//记录每个字符第一次出现的位置,这里即 i
map.set(char,i)
}else {
//出现过了,获取当前字符第一次出现的位置,存储在 s_arr
const direction = map.get(char)
s_arr[i] = direction
}
}
return s_arr
}
const s_pattern = getPatten(s)
const t_pattern = getPatten(t)
const result =s_pattern.every((s,index)=>s === t_pattern[index])
return result
};