# [LeetCode] 205. Isomorphic Strings 同构字符串

2021年09月15日 阅读数：1

Given two strings s and t, determine if they are isomorphic.html

Two strings are isomorphic if the characters in s can be replaced to get t.java

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.python

Example 1:app

```Input: s = `"egg", `t = `"add"`
Output: true
```

Example 2:post

```Input: s = `"foo", `t = `"bar"`
Output: false```

Example 3:url

```Input: s = `"paper", `t = `"title"`
Output: true```

Note:
You may assume both and have the same length.code

Java:

```public class Solution {
public boolean isIsomorphic(String s1, String s2) {
int[] m = new int[512];
for (int i = 0; i < s1.length(); i++) {
if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
}
return true;
}
}　　```

Java:

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

return true;
}
}　　```

Python: wo

```class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
ms, mt = {}, {}
for i in xrange(len(s)):
if ms.get(s[i]) != mt.get(t[i]):
return False
ms[s[i]] = i
mt[t[i]] = i

return True   　　```

Python:

```def isIsomorphic1(self, s, t):
d1, d2 = {}, {}
for i, val in enumerate(s):
d1[val] = d1.get(val, []) + [i]
for i, val in enumerate(t):
d2[val] = d2.get(val, []) + [i]
return sorted(d1.values()) == sorted(d2.values())

def isIsomorphic2(self, s, t):
d1, d2 = [[] for _ in xrange(256)], [[] for _ in xrange(256)]
for i, val in enumerate(s):
d1[ord(val)].append(i)
for i, val in enumerate(t):
d2[ord(val)].append(i)
return sorted(d1) == sorted(d2)

def isIsomorphic3(self, s, t):
return len(set(zip(s, t))) == len(set(s)) == len(set(t))

def isIsomorphic4(self, s, t):
return [s.find(i) for i in s] == [t.find(j) for j in t]

def isIsomorphic5(self, s, t):
return map(s.find, s) == map(t.find, t)

def isIsomorphic(self, s, t):
d1, d2 = [0 for _ in xrange(256)], [0 for _ in xrange(256)]
for i in xrange(len(s)):
if d1[ord(s[i])] != d2[ord(t[i])]:
return False
d1[ord(s[i])] = i+1
d2[ord(t[i])] = i+1
return True　　```

C++:

```class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = {0}, m2[256] = {0}, n = s.size();
for (int i = 0; i < n; ++i) {
if (m1[s[i]] != m2[t[i]]) return false;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return true;
}
};
```

[LeetCode] 290. Word Pattern 单词模式