next up previous
Next: Example: symmetric sequence of Up: Unit 11 Previous: Example: the last ones

Example: palindrome string

A string is said to be a palindrome if the string read from left to right is equal to the string read from right to left. For example, ignoring the difference between uppercase and lowercase letters, the string "iTopiNonAvevanoNipoti" is a palindrome, while the string "iGattiNonAvevanoCugini" is not so.

The following is an inductive characterization of a palindrome string:

Using such a characterization, we can implement a recursive method that verifies whether a string passed as a parameter is a palindrome.

public static boolean palindrome(String s) {
  if (s.length() <= 1)
    return true;
  else
    return (s.charAt(0) == s.charAt(s.length()-1)) &&
            palindrome(s.substring(1,s.length()-1));
}


next up previous
Next: Example: symmetric sequence of Up: Unit 11 Previous: Example: the last ones