// Two strings are isomorphic if characters in one can be replaced to get the other,
// while preserving the order.
import java.util.HashMap;
import java.util.Map;
public class IsomorphicStrings {
public static boolean areIsomorphic(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Character> mapST = new HashMap<>();
Map<Character, Character> mapTS = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
// Check mapping from s → t
if (mapST.containsKey(c1)) {
if (mapST.get(c1) != c2) return false;
} else {
mapST.put(c1, c2);
}
// Check mapping from t → s
if (mapTS.containsKey(c2)) {
if (mapTS.get(c2) != c1) return false;
} else {
mapTS.put(c2, c1);
}
}
return true;
}
public static void main(String[] args) {
System.out.println(areIsomorphic("egg", "add"));
System.out.println(areIsomorphic("foo", "bar"));
System.out.println(areIsomorphic("paper", "title"));
}
}
/*
run:
true
false
true
*/