Skip to content

Instantly share code, notes, and snippets.

@StephanieMak
Forked from XiaoxiaoLi/ReverseAString.java
Last active August 29, 2015 14:27
Show Gist options
  • Save StephanieMak/0127fbbce1be57584e0a to your computer and use it in GitHub Desktop.
Save StephanieMak/0127fbbce1be57584e0a to your computer and use it in GitHub Desktop.
#CC150 #CC150-chap1 1.2 Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
//1.2 Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
public class ReverseAString{
/** Time: O(n), Space O(n)
* Find the middle point of the array, swap each pair of char that is before
* and after the middle point with the same distance
*/
public static String reverseStr(String str) {
if (str == null || str.isEmpty()) {
return null;
}
// Turn the string into a char array
char[] chars = str.toCharArray();
int len = chars.length;
int mid = len / 2;// By default, int returns the floor of the division
// result
for (int i = 0; i < mid; i++) {
// Swap the values in position i and in position len-1-i
swap(chars, i, len - 1 - i);
}
return new String(chars);
}
private static void swap(char[] chars, int i, int j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
public static void main(String args[]) {
String str1 = "abc";
String str2 = "abcd";
System.out.println(reverseStr(str1));
System.out.println(reverseStr(str2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment