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: true
Example 2:
Input: s ="foo",
t ="bar"
Output: false
Example 3:
Input: s ="paper",
t ="title"
Output: true
Note:
You may assume both s and t have the same length.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
a2b, b2a = {}, {}
n = len(s)
for i in range(n):
a, b = s[i], t[i]
if (a in a2b and a2b[a] != b) or (b in b2a and b2a[b] != a):
return False
a2b[a] = b
b2a[b] = a
return True
class Solution {
public boolean isIsomorphic(String s, String t) {
int n = s.length();
Map<Character, Character> a2b = new HashMap<>();
Map<Character, Character> b2a = new HashMap<>();
for (int i = 0; i < n; ++i) {
char a = s.charAt(i), b = t.charAt(i);
if ((a2b.containsKey(a) && a2b.get(a) != b) || (b2a.containsKey(b) && b2a.get(b) != a)) return false;
a2b.put(a, b);
b2a.put(b, a);
}
return true;
}
}