beyondgrader.com Logo
DemoBrowseAboutTeamLogin

Isomorphic Strings With Map

Geoffrey Challen // 2022.8.0

Two strings are called isomorphic if there exists a one-to-one mapping from characters in one string to characters in the other.

For example, "aab" and "xxy" are isomorphic, because the one-to-one mapping {'a': 'x', 'b': 'y'}, when applied to "aab", yields "xxy". However, "acb" and "xxy" are not isomorphic, because the mapping {'a': 'x', 'c': 'x', 'b': 'y'} is not one-to-one, because 'x' appears twice as a value.

One way to think about it is that the mapping should allow us to transform back and forth between the two strings. After transforming "aab" to "xxy", we can invert the mapping to undo the transformation. However, after transforming "acb" to "xxy", we cannot undo the transformation.

Create a public class IsomorphicStrings that provides a single public static method areIsomorphic. It accepts two Strings and returns true if the Strings are isomorphic, and false otherwise. If either String is null, throw an IllegalArgumentException. Also note that you can begin with a simple length check to rule out certain cases.

A natural way to approach this problem is to use a Map<Character, Character>, and both java.util.Map and java.util.HashMap are available for this problem. You may also find sets useful, and can use java.util.Set and java.util.HashSet.