Page 431 - AP Computer Science A, 7th edition
P. 431

∗ @param end the index of the last character of the substring
∗ @return true if the substring is a palindrome, false otherwise
∗ Precondition: s contains no spaces, punctuation, or capitals.
∗/
private static boolean isPalindrome(String s, int start, int end)
Solution
(a) public Sentence(String str) {
sentence = str;
numWords = 1;
int k = str.indexOf(“ ”);
while (k != –1) //while there are still blanks in str
{
numWords++;
str = str.substring(k + 1); //substring after blank
k = str.indexOf(“ ”); //get index of next blank
} }
(b) private static boolean isPalindrome(String s, int start,
int end) {
if (start >= end) //substring has length 0 or 1 return true;
else {
String first = s.substring(start, start + 1); String last = s.substring(end, end + 1);
if (first.equals(last))
return isPalindrome(s, start + 1, end – 1); else
return false;











































































   429   430   431   432   433