Monday, January 12, 2015

Recursion Problem in Java: Reverse a sentence

Problem: Write a recursive function to reverse the words in a string, i.e., "cat is running"
becomes "running is cat".

    public String reverse(String str, int ctr){ 
     if(str.lastIndexOf(" ")==-1) return str;        
     return str.substring(str.lastIndexOf(" ")+1) + " " + 
        reverse(str.substring(0, str.lastIndexOf(" ")),ctr+1); }

Recursion Problem in Java: Reverse a word

Problem: Write a recursive function to reverse a string.
Ex. "programmer" becomes "remmargorp"

    public String reverse(String str){
    if(str.length()==0) return "";
    return str.substring(str.length()-1) + reverse(str.substring(0, str.length()-1));
    }