Last active
August 29, 2015 13:56
-
-
Save adohe-zz/9016089 to your computer and use it in GitHub Desktop.
different implementations of string reverse in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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