Rotate string counterclockwise

Posted on

Problem

Here is the function I have come up with. Any improvements possible?

E.g LeetCode -> rotate by 2 -> deLeetCo

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}

Solution

    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }

An easy optimization is to change this to

    for (int j = 1; j <= i; j++) {
        prefix.append(s.charAt(s.length() - j));
    }

You can go further if you like, e.g.

    for (int j = s.length() - 1, m = s.length - i; j >= m; j--) {
        prefix.append(s.charAt(j));
    }

But if you’re doing that, you might as well change

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}

to

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer();

    for (int j = s.length() - 1; j >= i; j--) {
        prefix.append(s.charAt(j));
    }

    return prefix.append(s.substring(0, i)).toString();
}

Now we only subtract from s.length() twice. Before we subtracted from it i + 1 times.

But I actually think that the best version is

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer(s.substring(i));

    return prefix.reverse().append(s.substring(0, i)).toString();
}

Now I can easily read this and see that we are reversing the last part of the string and appending the first part.

I’m not really feeling the rotateAntiClockWise name. That’s not really what we’re doing. We’re more mirrorSuffixToPrefix or something.

Leave a Reply

Your email address will not be published. Required fields are marked *