A palindrome is a string that reads the same backwards as forwards. For example, civic
, radar
, deed
, and racecar
are all palindromes. The definition I just gave is a non-recursive one: the string is equal to its reverse. Come up with a recursive definition of a palindrome, and write pseudocode for the following method. You can use indexing and range indexing to refer to characters and substrings of s
.
/** return true iff s[start..end] is a palindrome
* Pre: s is not null */
public boolean isPal(s, start, end) {
// TODO
}
Here’s the pseudocode for a factorial function:
/** return n!; pre: n >= 0 */
fact(n):
if n == 0:
return 1
return n * fact(n - 1)
What is the asymptotic runtime class of this function in terms of n
?
Recall the count_e
method, which processed the string one character at a time (i.e., in an incremental fashion):
/** returns # of ‘e’ in string s. Pre: s is not null. */
public int count_e(String s):
if s.length() == 0:
return 0;
= 0
first if s[0] == ‘e’:
= 1
first
return first + count_e(s[1..end])
Write a different version of this method that has the same spec, but solves the problem using the divide-and-conquer paradigm.
The Node
class below defines a singly-linked list node:
public class Node {
int value;
Node next;
}
Write a recursive implementation of the following method:
/** Reverse the order of the singly linked list with the given head node;
. Pre: head is not null. */
return the head node of the new listpublic static Node reverse(Node head) {
// your code here
}