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
Test cases in Scala
assert(!isPalindrome("abcd")) assert(isPalindrome("abcdcba")) assert(isPalindrome("abcddcba")) assert(isPalindrome(Array(1).toIndexedSeq)) assert(!isPalindrome(Array(1, 2).toIndexedSeq))
Algorithm in Scala
5 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
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 in Scala lets you quickly identify what you are looking for in a data, and also extract it.
.viewsyntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.
'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.