Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,

Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note: You may assume both s and t have the same length.

def isIsomorphic(s: String, t: String): Boolean = {
  if (s.length != t.length) false
  else if (s.length == 0) true
  else {
    var mapping = Map[Char, Char]()
    for (i <- 0 until s.length) {
      mapping.get(s(i)) match {
        case Some(j) => {
          if (j != t(i)) return false
        case None =>
          mapping += (s(i) -> t(i))

isIsomorphic("egg", "add")
isIsomorphic("foo", "bar")
isIsomorphic("paper", "title")

Last updated