Skip to content

Instantly share code, notes, and snippets.

@asethia
Last active July 25, 2018 19:23
Show Gist options
  • Save asethia/d2f7cb03adf1d8d3034e92d5bd5e9b61 to your computer and use it in GitHub Desktop.
Save asethia/d2f7cb03adf1d8d3034e92d5bd5e9b61 to your computer and use it in GitHub Desktop.
Implement an algorithm to determine if a string has all unique characters.
import scala.annotation.tailrec
/**
* find given string has unique characters
*
* Created by Arun Sethia on 5/21/18.
*/
trait UniqueCharacters {
//ASCII Characters 128
def isUnique(input: String): Boolean = {
val ascii: Array[Boolean] = Array.ofDim[Boolean](128)
@tailrec
def uniqueness(chars: List[Char],returnValue:Boolean): Boolean = {
chars match {
case Nil => returnValue
case h :: _ => {
val charIndex = h.toInt
if (ascii(charIndex)) {
uniqueness(Nil,false)
}
else {
ascii(charIndex) = true
uniqueness(chars.tail,true)
}
}
}
}
uniqueness(input.toList,false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment