My Avatar

Shilong ZHAO

[s 99] p06 check if a list is palindrome

2020-06-22 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Find out whether a list is a palindrome.

Example:

scala> isPalindrome(List(1, 2, 3, 2, 1))
res0: Boolean = true
def isPalindrome[T](list: List[T]): Boolean = {

    @scala.annotation.tailrec
    def palindrome(from:Int, to:Int): Boolean = {
      if (from >= to) true
      else if (list(from) == list(to)) palindrome(from + 1, to - 1)
      else false
    }

    palindrome(0, list.size - 1)
}

isPalindrome(Nil)
isPalindrome(List(1,2,3))
isPalindrome(List(1,2,3,2,1))
def isPalindromeReverse[T](a: List[T]): Boolean = a == a.reverse
isPalindrome(Nil)
isPalindromeReverse(List(1,2,3))
isPalindromeReverse(List(1,2,3,2,1))
def isPalindrome3[T](a: List[T]): Boolean = a match {
    case Nil => true
    case List(x) => true
    case _ => a.head == a.last && isPalindrome3(a.tail.init)
}

isPalindrome3(Nil)
isPalindrome3(List(1,2,3))
isPalindrome3(List(1,2,3,2,1))