Skip to content

Instantly share code, notes, and snippets.

@asethia
Created July 5, 2018 14:54
Show Gist options
  • Save asethia/78ca72c08c1d5a8720ddd9d2d7529a7b to your computer and use it in GitHub Desktop.
Save asethia/78ca72c08c1d5a8720ddd9d2d7529a7b to your computer and use it in GitHub Desktop.
Given two strings, write a method to decide if one is a permutation of the other.
import scala.annotation.tailrec
/**
* given two strings, write a method to decide if one is a permutation of the other.
* Created by Arun Sethia on 7/5/18.
*/
trait AnagramString {
final val ASCII_CHAR_LEN: Int = 128
/**
* check given two strings are permutation of the other.
* @param input1
* @param input2
* @return
*/
def isAnagramString(input1: String, input2: String) = {
val arrayOfCount: Array[Int] = Array.ofDim[Int](ASCII_CHAR_LEN)
val i = input1.length - 1
val j = input2.length - 1
if (i != j) false
else {
for (c <- 0 to i) {
arrayOfCount(input1(c).toInt) = arrayOfCount(input1(c).toInt) + 1
arrayOfCount(input2(c).toInt) = arrayOfCount(input2(c).toInt) - 1
}
checkAnagram(arrayOfCount, 0, true)
}
}
@tailrec
private def checkAnagram(anagramFlag: Array[Int], count: Int, returnFlag: Boolean): Boolean = {
if (anagramFlag.length == 0 || !returnFlag) returnFlag
else if (count == anagramFlag.length) returnFlag
else checkAnagram(anagramFlag, count + 1, anagramFlag(count) == 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment