mastheadIcon

Recursive String Reversal

Stack Demo

    
    public static String r(String text, int lastNdx){
        if(lastNdx < 0){
            return "";
        }else{
            return text.substring(lastNdx, lastNdx+1) + r(text, lastNdx-1);
        }
    }//end method r
    
        

String reversed = r("abcd", 3);

0 1 2 3
a b c d
Call: Stack Statement Returns: Result:
r(text, -1) → "" ""
r(text, 0) → a + r(text, -1) a + "" = a
r(text, 1) → b + r(text, 0) b + a = ba
r(text, 2) → c + r(text, 1) c + ba = cba
r(text, 3) → d + r(text, 2) d + cba = dcba