Created
June 29, 2019 18:41
-
-
Save shixiaoyu/677dc4123da8b32de7696e3e096a6097 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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