In: Computer Science
Write a recursive method that takes a String argument and recursively prints out each word in the String on a different line.
Note: You will need to use methods such as indexOf() and substring() within the String class to identify each word and the remaining string.
For example, if the input was “the cat purred”, then the method would print the following to the Java console:
the
cat
purred
Challenge Problem
Write a recursive method that takes a string as an input and returns a boolean value that tells you whether the string is a palindrome. A palindrome is a word/sentence that when read backwards is the same as the original word/sentence.
Some example palindromes: “civic”, “radar”, “deleveled”, “a man, a plan, a canal: Panama” (ignore the punctuation)
PreviousNext
Hi, Please find my implementation.
I have implemented both questions in same file as a function/method.
public class StringoOperation {
public static void printWordRecursive(String str){
// Base case
if(str == null || str.trim().length() == 0)
return;
int index = str.indexOf(' ');
// this is the last word
if(index == -1){
System.out.println(str);
return;
}else{
// printing current word
System.out.println(str.substring(0, index));
// calling recursively
printWordRecursive(str.substring(index+1));
}
}
public static boolean isPalindrome(String str){
if(str == null || str.trim().length() == 0)
return false;
int i=0;
int j = str.length()-1;
while(i < j){
char ith = Character.toLowerCase(str.charAt(i));
char jth = Character.toLowerCase(str.charAt(j));
if(Character.isDigit(ith) || Character.isLetter(ith)){
if(Character.isDigit(jth) || Character.isLetter(jth)){
//System.out.println(ith+" "+jth);
if(ith != jth) // not palindrome
return false;
i++;
j--;
}else{// skipping special characters
j--;
}
}else{ // skipping special characters
i++;
}
}
return true;
}
public static void main(String[] args) {
printWordRecursive("This is a sample statemmets");
System.out.println();
System.out.println("Is 'madam' palindrome ? "+isPalindrome("madam"));
System.out.println("Is 'mada mn' palindrome ? "+isPalindrome("mada mn"));
System.out.println("Is 'deleveled' palindrome ? "+isPalindrome("deleveled"));
System.out.println("Is 'a man, a plan, a canal: Panama' palindrome ? "+
isPalindrome("a man, a plan, a canal: Panama"));
}
}
/*
Sample run:
This
is
a
sample
statemmets
Is 'madam' palindrome ? true
Is 'mada mn' palindrome ? false
Is 'deleveled' palindrome ? true
Is 'a man, a plan, a canal: Panama' palindrome ? true
*/