pathikrit / scalgos

algorithms in scala
434 stars 129 forks source link

Manacher's algorithm #15

Open pathikrit opened 7 years ago

pathikrit commented 7 years ago
// O(n^3) version
def countPalindromes3(s: String): Int =
  (1 to s.length).flatMap(s.sliding).count(t => t.reverse == t)
// O(n^2) version
def countPalindromes2(s: String): Int = {

  def countBetween(left: Int, right: Int): Int = {
    if (s.isDefinedAt(left) && s.isDefinedAt(right) && s(left) == s(right)) {
      1 + countBetween(left - 1, right + 1)
    } else {
      0
    }
  }

  s.indices.map(i => countBetween(left = i, right = i) + countBetween(left = i, right = i+1)).sum
}

// O(n) version
def countPalindromes1(s: String): Int = {
  // Manacher's algo - non trivial
  ???
}```