Recursion

AP Computer Science A· difficulty 3/5

public static boolean isPal(String s) {
  if (s.length() <= 1) return true;
  if (s.charAt(0) != s.charAt(s.length() - 1)) return false;
  return isPal(s.substring(1, s.length() - 1));
}
// call: isPal("level")

What does it return?

  • A

    null

  • B

    stack overflow

  • C

    true

    check_circle
  • D

    false

Explanation

Each recursive call peels matching outer characters; "level" is a palindrome.

Want 10 more like this — adaptive to your weak spots?

Related questions