-
-
Save gaoyike/50d11d25f2f59deb3150 to your computer and use it in GitHub Desktop.
1.2
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
/** | |
* 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())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the Space Complexity is also O(n), because the toCharArray() will traverse all the character in the String.