Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Last active August 29, 2015 14:02
Show Gist options
  • Save UncleGarden/85509dad7178cde74c50 to your computer and use it in GitHub Desktop.
Save UncleGarden/85509dad7178cde74c50 to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 1.2 Implement a function void reverse(char* str) in C or C++ which reverses a
* null-terminated string.
*
* @author Jiateng
*/
public class CC1_2 {
//Time O(n), Space O(n)
public static String reverse1(String target) {
StringBuilder result = new StringBuilder();
//directly add from the end to the start
for (int i = target.length() - 1; i >= 0; i--) {
result.append(target.charAt(i));
}
return result.toString();
}
//Time O(n), Space O(1)
public static String reverse2(String target) {
//make an array
char[] array = target.toCharArray();
//start
int left = 0;
//end
int right = array.length - 1;
while (left < right) {
//swap
char temp = array[right];
array[right] = array[left];
array[left] = temp;
//move from both start and end to the middle
left++;
right--;
}
return String.valueOf(array);
}
public static void main(String[] args) {
String target = "sodufhosdg";
System.out.println(reverse1(target));
System.out.println(reverse2(target));
}
}
@jyuan
Copy link

jyuan commented Jun 23, 2014

In StringBuffer type, there is a reverse() method to fast reverse the stringBuffer.

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