Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created June 29, 2019 18:41
Show Gist options
  • Save shixiaoyu/677dc4123da8b32de7696e3e096a6097 to your computer and use it in GitHub Desktop.
Save shixiaoyu/677dc4123da8b32de7696e3e096a6097 to your computer and use it in GitHub Desktop.
public boolean isIsomorphic(String a, String b) {
if (a == null || b == null || a.length() != b.length()) {
return false;
}
Map<Character, Character> lookup = new HashMap<>();
Set<Character> dupSet = new HashSet<>();
for (int i = 0; i < a.length(); i++) {
char c1 = a.charAt(i);
char c2 = b.charAt(i);
if (lookup.containsKey(c1)) {
if (c2 != lookup.get(c1)) {
return false;
}
} else {
lookup.put(c1, c2);
// this to prevent different c1s map to the same c2, it has to be a bijection mapping
if (dupSet.contains(c2)) {
return false;
}
dupSet.add(c2);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment