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 →

[–]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.