Check if a String is a palindrome in immutable Scala

Algorithm goal

A String is a palindrome when reversing it yields it itself.

For example 'ab' is not a palindrome, but 'aba', and 'abba' are.

This problem is similar to CheckArrayIsAPalindrome and CheckNumberIsAPalindrome

Explanation

As in CheckArrayIsAPalindrome, we must note that we can remap an Array to its reverse without allocating a new array (efficient!).

The same can, in fact, be done for a String, as String meets a specification of 'IndexedSeq' (which is also met by an Array). (this is © from www.scala-algorithms.com)

To our advantage, we utilise the fact that a palindrome is its reverse, and that 'IndexedSeq' can be converted into a view, and then re-mapped into a reverse.

Scala Concepts & Hints

Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

assert("Hello World".collect {
  case character if Character.isUpperCase(character) => character.toLower
} == "hw")

Read more

Zip

'zip' allows you to combine two lists pair-wise (meaning turn a pair of lists, into a list of pairs)

It can be used over Arrays, Lists, Views, Iterators and other collections.

assert(List(1, 2, 3).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6, 3 -> 7))

assert(List(1, 2).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6))

assert(List(5, 6).zipWithIndex == List(5 -> 0, 6 -> 1))

Read more

View

The .view syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.

Read more

Algorithm in Scala

7 lines of Scala (version 2.13), showing how concise Scala can be!

This solution is available for purchase!

'Unlimited Scala Algorithms' gives you access to all solutions!

Upon purchase, you will be able to Register an account to access solutions on multiple devices.

Test cases in Scala

assert(!isPalindrome("abcd"))
assert(isPalindrome("abcdcba"))
assert(isPalindrome("abcddcba"))
assert(isPalindrome(Array(1).toIndexedSeq))
assert(!isPalindrome(Array(1, 2).toIndexedSeq))
def isPalindrome[T](indexedSeq: IndexedSeq[T]): Boolean = ???