Skip to content

Instantly share code, notes, and snippets.

@VallaDanger
Last active April 23, 2016 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VallaDanger/64df87b3a585c11430007a52deb4d147 to your computer and use it in GitHub Desktop.
Save VallaDanger/64df87b3a585c11430007a52deb4d147 to your computer and use it in GitHub Desktop.
Reverse String [for & recursive]
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;
}
}
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