Skip to content

Instantly share code, notes, and snippets.

@gaoyike
Last active August 29, 2015 14:02
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 gaoyike/50d11d25f2f59deb3150 to your computer and use it in GitHub Desktop.
Save gaoyike/50d11d25f2f59deb3150 to your computer and use it in GitHub Desktop.
1.2
/**
* Created by Readman on 6/15/14.
*/
public class reversesString {
/*
time: n
space: 1
by the way, i have no idea about the time complexity of valueof method. if someone know, plz msg me. thx
* */
public static String reverses (char[] str) {
int i = 0;
int j = str.length - 1;
while (i < j) {
if (str[i] != str[j]) {
swap(str, i , j);
}
i ++;
j --;
}
return String.valueOf(str);
}
public static void swap (char[] str, int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
public static void main(String[] args) {
String s = "abc";
System.out.println(reverses(s.toCharArray()));
}
}
@jyuan
Copy link

jyuan commented Jun 23, 2014

I think the Space Complexity is also O(n), because the toCharArray() will traverse all the character in the String.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment