Use two hash maps to track bidirectional character mappings between strings.
1class Solution {
2 public boolean isIsomorphic(String s, String t) {
3 if (s.length() != t.length()) return false;
4
5 Map<Character, Character> mapS = new HashMap<>();
6 Map<Character, Character> mapT = new HashMap<>();
7
8 for (int i = 0; i < s.length(); i++) {
9 char cs = s.charAt(i);
10 char ct = t.charAt(i);
11
12 if (mapS.containsKey(cs)) {
13 if (mapS.get(cs) != ct) return false;
14 } else {
15 mapS.put(cs, ct);
16 }
17
18 if (mapT.containsKey(ct)) {
19 if (mapT.get(ct) != cs) return false;
20 } else {
21 mapT.put(ct, cs);
22 }
23 }
24
25 return true;
26 }
27}