Last active
April 23, 2016 01:04
-
-
Save VallaDanger/64df87b3a585c11430007a52deb4d147 to your computer and use it in GitHub Desktop.
Reverse String [for & recursive]
This file contains hidden or 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 class Main { | |
public static void main(String[] args) throws Exception { | |
System.out.println(reverse("0123456789")); | |
} | |
private static String reverse(String str) { | |
int size; | |
if((str == null) || (size = str.length()) == 0) { | |
return str; | |
} else if(size == 1) { | |
return str; | |
} | |
return new String(swap(str.toCharArray(), 0, size-1)); | |
} | |
private static char[] swap(char[] str, int i, int j) { | |
char c = str[i]; | |
str[i] = str[j]; | |
str[j] = c; | |
return (i < j)? swap(str, ++i, --j) : str; | |
} | |
} |
This file contains hidden or 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 class Main { | |
public static void main(String[] args) throws Exception { | |
System.out.println(reverse("0123456789")); | |
} | |
private static String reverse(String str) { | |
int size; | |
if((str == null) || (size = str.length()) == 0) { | |
return str; | |
} else if(size == 1) { | |
return str; | |
} | |
char[] _str = str.toCharArray(); | |
char c; | |
for(int i = 0, j = size-1; i < j; i++, j--) { | |
c = _str[i]; | |
_str[i] = _str[j]; | |
_str[j] = c; | |
} | |
return new String(_str); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment