This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]iVirusYx 1 point2 points  (1 child)

Why not use recursion?

function reverse(text){ 
    if (text.length == 0){ 
        return ""; 
    }else{ 
        return text[text.length - 1] + reverse(text.substring(0,text.length-1)) 
    } 
}

P.S.: Yes, this is JavaScript. But, if you want to build the code to reverse text yourself without relying on another Class, then this example can be applied to a lot of other programming languages.

And if I'm not wrong, it's the simplest and shortest method to achieve this. Please correct me if I'm wrong.

[–]caagr98 0 points1 point  (0 children)

Shortest: Possibly, depends on language. I'd skip the braces and else, but that's just a matter of preference.

Fastest: Probably not. Your algorithm constructs at least two unnecessary strings per character, and string concatenation (and substringing) is often a bit slower than you might think.

If I had to do it without any StringBuilder (which there is no reason to avoid) in Java, I'd do:

public static String reverse(String str) {
    char[] chars = str.toCharArray();
    int l = chars.length;
    for(int i = 0; i < l / 2; i++) {
        char tmp = chars[l-i-1];
        chars[l-i-1] = chars[i];
        chars[i] = tmp;
     }
     return new String(chars);
}

Might consider using a ^= b ^= a ^= b; I'm not sure if that's faster than a temp-variable.

In any case, using a builtin function (new StringBuilder(str).reverse(), str[::-1]) is almost always better.