Skip to content

Instantly share code, notes, and snippets.

@divyakali
Last active August 30, 2015 18:41
Show Gist options
  • Save divyakali/46affdcddc84f554a430 to your computer and use it in GitHub Desktop.
Save divyakali/46affdcddc84f554a430 to your computer and use it in GitHub Desktop.
Checks if two strings are isomorphic i.e if the characters in source can be replaced to transform into target. The oder should be preserved. Characters can map to themselves but two different characters cannot map to the same character.Checks if two strings are isomorphic i.e if the characters in source can be replaced to transform into target. …
import java.util.HashMap;
public class Isomorphism {
/**
* Checks if two strings are isomorphic
*/
public static boolean isIsomorphic(String source, String target) {
if (source == null || target == null)
return false;
if (source.length() != target.length())
return false;
HashMap<Character, Character> transformationMap = new HashMap<Character, Character>();
for (int i = 0; i < source.length(); i++) {
char sch = source.charAt(i);
char tch = target.charAt(i);
if (transformationMap.containsKey(sch)) {
char val = transformationMap.get(sch);
if (val != tch)
return false;
} else {
if (!transformationMap.containsValue(tch))
transformationMap.put(sch, tch);
else
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isIsomorphic("egg", "add"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment