Kotlinlearncs.online LogoJava
Return to List

Test Writing: Isomorphic Strings With Map

Created By: Geoffrey Challen
/ Version: 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.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a public class named TestIsomorphicStrings with a single non-private class method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Java's assert method