Wednesday, 5 December 2012

Week 9-Palindrome


I found it difficult to understand the idea of palindrome. To checkout whether a string is a palindrome, we can simply write the define as below:

(define (palindrome? s)
  (cond
    [(equal? (string-length s) 1) true]
    [else
     (and (equal? (substring s 0 1)
                  (substring s (sub1 (string-length s))))
          (palindrome? (substring s 1 (sub1 (string-length s)))))]))

However, I cannot understand the “define” at first. I understand the first condition [(equal? (string-length s) 1) true] is to check if the string has only one character. One character is always a palindrome. For longer string, we should check the second condition. It is basically check the first and last character, second and second last and etc. is the same. However, it has another (palindrome? (substring s 1 (sub1 (string-length s)))) in the second condition.
I then realized that the palindrome inside the second condition is to check the second and second last characters in the string ect.  

No comments:

Post a Comment