# 205. Isomorphic Strings 同构字符串

@TOC

## # 题目描述

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.

## # 解题方法

### # 字典保存位置

``````public class Solution {
public boolean isIsomorphic(String s, String t) {
int[] m1 = new int[256];
int[] m2 = new int[256];
int len = s.length();
for(int i = 0; i < len; i++){
if(m1[s.charAt(i)] != m2[t.charAt(i)]){
return false;
}
m1[s.charAt(i)] = i + 1;
m2[t.charAt(i)] = i + 1;
}
return true;
}
}
``````

### # 字典保存映射

``````class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
m = dict()
for i, c in enumerate(s):
if c in m:
if t[i] != m[c]:
return False
else:
m[c] = t[i]
m = dict()
for i, c in enumerate(t):
if c in m:
if s[i] != m[c]:
return False
else:
m[c] = s[i]
return True
``````

``````class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
m = dict()
n = dict()
for i, c in enumerate(s):
if c in m and m[c] != t[i]:
return False
if t[i] in n and c != n[t[i]]:
return False
m[c] = t[i]
n[t[i]] = c
return True
``````

## # 日期

2017 年 5 月 15 日 2018 年 11 月 24 日 —— 周六快乐