Scala algorithm: Check if a String is a palindrome

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

  1. 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")
    
  2. View

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

  3. 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))
    
    assert(List(5, 6).zipAll(List('A'), 9, 'Z') == List(5 -> 'A', 6 -> 'Z'))
    
    assert(List(5).zipAll(List('A', 'B'), 1, 'Z') == List(5 -> 'A', 1 -> 'B'))
    

Algorithm in Scala

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

This solution is available for access!

or

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

Upon purchase, you will be able to Register an account to access all the algorithms 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))

View the rest of Scala algorithms