Check String Permutation

Given two strings, write a method to decide if ones is a permutation of the other

import scala.collection.mutable.Map

def isPermutation(s1: String, s2: String): Boolean = {
  if (s1.length != s2.length) false
  else if (s1.isEmpty) true
  else {
    val charMap = Map[Char, Int]() withDefaultValue 0
    for (i <- 0 until s1.length; j <- 0 until s2.length) {
      charMap(s1(i)) += 1
      charMap(s2(j)) -= 1
    }
    charMap.values.forall(_ == 0)
  }
}

isPermutation("", "")
isPermutation("abcd", "dcba")
isPermutation("abcd", "ecba")

Last updated