Skip to content

Instantly share code, notes, and snippets.

@leonw007
Last active August 29, 2015 14:18
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 leonw007/4b1b10602e38f2e6b6c9 to your computer and use it in GitHub Desktop.
Save leonw007/4b1b10602e38f2e6b6c9 to your computer and use it in GitHub Desktop.
cc150-1.2
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