|
|
|
|
|
public static void main(String[] args)
{
nPrintln("Hello World", 4);
}
public static void nPrintln(String message, int times)
{
if ( times == 0 )
{
return;
}
else
{
System.out.println(message); // Reduce the problem
nPrintln(message, times-1); // So that we can recurse
}
}
|
|
|
Let write the code for the base case first:
public static boolean isPalindrome(String w)
{
if ( w.length() <= 1 )
{ // base case
return true;
}
else
{
// Reduce the problem
int lastPos = w.length() - 1;
if ( w.charAt(0) != w.charAt(lastPos) )
return false; // w is not a palindrome
// After reducing problem with 1 step, use recursion
boolean ans = isPalindrome( w.substring(1, lastPos) );
return ans;
}
}
|
A word of length ≤ 1 is always a palindrome:
public static boolean isPalindrome(String w)
{
if ( w.length() <= 1 )
{ // base case
return true;
}
else
{
// Reduce the problem
int lastPos = w.length() - 1;
if ( w.charAt(0) != w.charAt(lastPos) )
return false; // w is not a palindrome
// After reducing problem with 1 step, use recursion
boolean ans = isPalindrome( w.substring(1, lastPos) );
return ans;
}
}
|
Next: in order to use recursion, we must reduce the problem to a smaller one.
A word of length ≤ 1 is always a palindrome:
public static boolean isPalindrome(String w)
{
if ( w.length() <= 1 )
{ // base case
return true;
}
else
{
// Reduce the problem: check 1st and last char
int lastPos = w.length() - 1;
if ( w.charAt(0) != w.charAt(lastPos) )
return false; // w is not a palindrome
// We still need to check the rest of the word !
boolean ans = isPalindrome( w.substring(1, lastPos) );
return ans;
}
}
|
After reducing the problem, we can use recursion (we have a smaller version of the original problem)
Use recursion to solve the correct smaller problem:
public static boolean isPalindrome(String w)
{
if ( w.length() <= 1 )
{ // base case
return true;
}
else
{
// Reduce the problem: check 1st and last char
int lastPos = w.length() - 1;
if ( w.charAt(0) != w.charAt(lastPos) )
return false; // w is not a palindrome
// After reducing problem with 1 step, use recursion
boolean ans = isPalindrome( w.substring(1, lastPos) );
return ans;
}
}
|
Next slide contains code that you can run in BlueJ
public static void main(String[] args)
{
boolean r = isPalindrome("abcba");
}
public static boolean isPalindrome(String w)
{
if ( w.length() <= 1 )
{ // base case
return true;
}
else
{
// Reduce the problem: check 1st and last char
int lastPos = w.length() - 1;
if ( w.charAt(0) != w.charAt(lastPos) )
return false; // w is not a palindrome
// After reducing problem with 1 step, use recursion
boolean ans = isPalindrome( w.substring(1, lastPos) );
return ans;
}
}
|