Unique String

Implement an algorithm to determine if a string has all unique characters,What if you cannot use additional data structures?

import scala.collection.mutable.Map

def uniqueWithMap(s:String): Boolean = {
  val charMap = Map[Char, Int]()
  for (i <- 0 until s.length) {
    charMap.get(s(i)) match {
      case Some(j) => return false
      case None => charMap += (s(i) -> i)
    }
  }
  true
}

def uniqueWithBitMask(s:String): Boolean = {
  var code_pt,checker = 0
  for (i <- 0 until s.length) {
    code_pt = 1 << (s(i).toInt - 'a'.toInt)
    if ((checker & code_pt) > 0) return false
    checker |= code_pt
  }
  true
}

Last updated