Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Last active August 29, 2015 13:56
Show Gist options
  • Save adohe-zz/9016089 to your computer and use it in GitHub Desktop.
Save adohe-zz/9016089 to your computer and use it in GitHub Desktop.
different implementations of string reverse in Java
public String reverse(String str) {
if(str == null)
throw new NullPointerException("null");
if(str.length() <= 1)
return str;
return new StringBuffer(str).reverse().toString();
}
public String reverseTwo(String str) {
if(str == null)
throw new NullPointerException("null");
if(str.length() <= 1)
return str;
return reverseTwo(str.subString(1)) + str.chartAt(0);
}
public String reverseThree(String str) {
if(str == null)
throw new NullPointerException("null");
if(str.length() <= 1)
return str;
StringBuffer sb = new StringBuffer(str.length());
for(int i = str.length() - 1; i >= 0; i--) {
sb.append(str.chartAt(i));
}
return sb.toString();
}
//Also another implementations...
public String reverseFour(char[] value) {
if(value == null)
throw new NullPointerException("null");
if(value.length == 1)
return new String(value);
for(int i = (value.length - 1) >>1; i >= 0; i--) {
char temp = value[i];
value[i] = value[value.length - 1 - i];
value[value.length - 1 - i] = temp;
}
return new String(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment