4
\$\begingroup\$

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();
}
asked Mar 20, 2017 at 2:03
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Why isn't the expected result deLeetCo? That is what you get if you rotate the characters. Is the source of this challenge this question from LintCode? If so, then you've misread the problem. \$\endgroup\$ Commented Mar 20, 2017 at 4:48
  • \$\begingroup\$ @JS1 - Thanks for pointing out the error in question. I have edited it. \$\endgroup\$ Commented Mar 20, 2017 at 9:38

1 Answer 1

6
\$\begingroup\$
 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.

answered Mar 20, 2017 at 3:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.