Last active
August 29, 2015 14:18
-
-
Save leonw007/4b1b10602e38f2e6b6c9 to your computer and use it in GitHub Desktop.
cc150-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
package ch1; | |
/* | |
1.2 Implement a function void reverse(char* str) in C or C++ which reverses a nullterminated string. | |
* We used a temp variable to exchange the i character with leng-1-i character | |
* One way to do this is our method | |
* char[] chars = str.toCharArray(); | |
* String newStr = String.valueOf(chars); | |
* | |
* We can also use Stringbuilder to change a character in a string | |
* StringBuilder myName = new StringBuilder("domanokz"); | |
* myName.setCharAt(4, 'x'); | |
Time Complexity O(n) Space O(1) | |
*/ | |
public class ReverseString { | |
public static String reverse(String str) { | |
char temp; | |
char[] chars = str.toCharArray(); | |
for(int i=0; i<str.length()/2; i++) { | |
temp = chars[i]; | |
chars[i] = chars[str.length()-1-i]; | |
chars[str.length()-1-i] = temp; | |
} | |
return String.valueOf(chars); | |
} | |
public static void main(String[] args) { | |
String test = "abcdef"; | |
test = reverse(test); | |
System.out.println(test); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment