Scala String Equality Question from Programming Interview

前端 未结 4 864
终归单人心
终归单人心 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:22

    Here is a version with a single recursive function and no additional classes or libraries. This is linear time and constant memory.

    def compare(a: String, b: String): Boolean = {
      @tailrec
      def loop(aIndex: Int, aDeletes: Int, bIndex: Int, bDeletes: Int): Boolean = {
        val aVal = if (aIndex < 0) None else Some(a(aIndex))
        val bVal = if (bIndex < 0) None else Some(b(bIndex))
    
        if (aVal.contains('/')) {
          loop(aIndex - 1, aDeletes + 1, bIndex, bDeletes)
        } else if (aDeletes > 0) {
          loop(aIndex - 1, aDeletes - 1, bIndex, bDeletes)
        } else if (bVal.contains('/')) {
          loop(aIndex, 0, bIndex - 1, bDeletes + 1)
        } else if (bDeletes > 0) {
          loop(aIndex, 0, bIndex - 1, bDeletes - 1)
        } else {
          aVal == bVal && (aVal.isEmpty || loop(aIndex - 1, 0, bIndex - 1, 0))
        }
      }
    
      loop(a.length - 1, 0, b.length - 1, 0)
    }
    

提交回复
热议问题