Scala String Equality Question from Programming Interview

前端 未结 4 866
终归单人心
终归单人心 2021-02-12 19:52

Since I liked programming in Scala, for my Google interview, I asked them to give me a Scala / functional programming style question. The Scala functional style question that I

4条回答
  •  一生所求
    2021-02-12 20:07

    If the goal is minimal memory footprint, it's hard to argue against iterators.

    def areSame(a :String, b :String) :Boolean = {
      def getNext(ci :Iterator[Char], ignore :Int = 0) : Option[Char] =
        if (ci.hasNext) {
          val c = ci.next()
          if (c == '/')        getNext(ci, ignore+1)
          else if (ignore > 0) getNext(ci, ignore-1)
          else                 Some(c)
        } else None
    
      val ari = a.reverseIterator
      val bri = b.reverseIterator
      1 to a.length.max(b.length) forall(_ => getNext(ari) == getNext(bri))
    }
    

    On the other hand, when arguing FP principals it's hard to defend iterators, since they're all about maintaining state.

提交回复
热议问题