fib is straightforward fib are quite fast fib(6)
fib(6) calls fib(3) three times f1 = 1; f2 = 1; fnew = f1 +f2; f2 = f1; f1 = fnew; ...
isPalindrome performs only slightly better than
recursive solution
isPalindrome Methodpublic boolean isPalindrome()
{
int start = 0;
int end = text.length() - 1;
while (start < end)
{
char first = Character.toLowerCase(text.charAt(start));
char last = Character.toLowerCase(text.charAt(end);
if (Character.isLetter(first) && Character.isLetter(last))
{
// Both are letters.
if (first == last)
{
start++;
end--;
}
else
{
return false;
}
}
if (!Character.isLetter(last)) { end--; }
if (!Character.isLetter(first)) { start++; }
}
return true;
}
Consider the triangle number computation in the
Triangle.getArea method.
1 + 2 + 3 +
. . . + widthwidth * (width
+ 1) / 2. "eat" has six permutations:
"eat" "eta" "aet" "ate" "tea" "tae"
You will define a class with a recursive method. Here is the start of the class
public class PermutationGenerator
{
private String word;
/**
Constructs a permutation generator.
@param aWord the word to permute
*/
public PermutationGenerator(String aWord)
{
word = aWord;
}
You will need an array list to hold all the permutations
public ArrayListgetPermutations() { ArrayList permutations = new ArrayList ();
// The empty string has a single permutation: itself
if (word.length() == 0)
{
permutations.add(word);
return permutations;
}
'e' , then
'a', then 't''e', we need to find all
permutations of "at"getPermutations method: loop through all positions in the word to be
permuted String shorterWord = word.substring(0, i) + word.substring(i + 1);
PermutationGenerator shorterPermutationGenerator
= new PermutationGenerator(shorterWord);
ArrayList<String> shorterWordPermutations
= shorterPermutationGenerator.getPermutations();
for (String s : shorterWordPermutations)
{
permutations.add(word.charAt(i) + s);
}
What are all permutations of the four-letter word beat?
b followed by the six permutations of eat, e
followed by the six permutations of bat, a followed by
the six permutations of bet, and t followed by the six
permutations of bea